首页 > 解决方案 > MYSQL - 具有和不具有子行的产品的定价过滤器

问题描述

好的,所以我有一个存储所有产品的表。产品分为三类;“简单”、“可配置”和“变体”。

简单和变体产品只是具有“价格”列和可选的“销售价格”列的单行。

可配置产品的“price”和“sale_price”列的值为零,但具有子(变体)产品行(由“parent_id”列连接)。

我想做的是根据价格创建一个过滤器。如果产品具有“sale_price”值,则应使用该值而不是“price”值。这适用于简单的产品:

select `products`.*, 
`lookup_product_categories`.`category_id` as `pivot_category_id`, 
`lookup_product_categories`.`product_id` as `pivot_product_id`
from `products` 
inner join `lookup_product_categories` on `products`.`id` = `lookup_product_categories`.`product_id` 
where `lookup_product_categories`.`category_id` = '38' 
and (
    `type` = 'simple' 
    and 
    IF (
        `sale_price` > 0,
        `sale_price` >= 30 AND `sale_price` <= 150,
        `price` >= 30 AND `price` <= 150
    ) 
) 
and `active` = '1' 
and `valid` = '1' 
and `products`.`deleted_at` is null 
order by `created_at` desc

我现在需要做的是在“可配置”产品的情况下获取子产品,确定每个应该使用促销价还是正常价格,然后如果至少有一个子产品在过滤范围内,则返回父可配置产品, 在这种情况下; 在 30.00 和 150.00 之间。

提前致谢。我完全坚持这一点。我已经尝试过内部连接,但我不能完全正确地使用语法。

标签: mysqldatabasejoinsuminner-join

解决方案


我假设您在表格中有以下列

id | type | sale_price | price | parent_id

没有样本数据很难编写查询,但您可以尝试以下操作:

select * from my_table t1
where (type in ('simple', 'variant') and sale_price is not null and sale_price between 30 and 150)
   or (type in ('simple', 'variant') and sale_price is null and price between 30 and 150)
   or (type = 'configurable' and exists(
        select 1 from my_table
        where (t1.parentid = id and sale_price is not null and sale_price between 30 and 150)
           or (t1.parentid = id and sale_price is null and price between 30 and 150)
      ));

推荐阅读