SQL获取所有筛选的项目

时间:2015-04-03 11:32:56

标签: sql postgresql laravel filter

我从表中获取数据时遇到问题,其中每个项必须匹配来自另一个表的过滤器需求,其中product_id,feature_category_id和feature_option_id之间存在关系。

EG。以下是该帮助程序表的示例插入:

id = 1
product_id = 10
feature_category_id = 100 - it's name of "feature category" eg. dimensions, weight etc.
feature_option_id = 1001 - it's product value of feature category eg. this product with id 10 have dimensions of 100x100 and it's id in another table is 1001 so it's that value.

现在我需要获得符合这些功能选项要求的所有产品。例如。我从搜索表单中选择给我所有尺寸为100x100且重量为1kg的产品,因此查询应该做一些事情来检查表格中的这些数据。

我尝试了一些东西,但只有1个product.features.feature_category_id才有用。如果where为2或更多,则该类型的子句返回0行。

select distinct 
    "products".*, "product_categories.*"
from 
    "products" 
inner join 
    "product_categories" on "products"."category_id" = "product_categories"."id" 
left join 
    "product_features" on "products"."id" = "product_features"."product_id" 
where 
    "products"."category_id" in (58) and 
    ((product_features.feature_category_id = 1 
      and product_features.feature_option_id = 58) 
     and (product_features.feature_category_id = 46 
          and product_features.feature_option_id = 62))

1 个答案:

答案 0 :(得分:0)

您可以使用group byhaving

获取符合条件的产品
select p.id
from products p join
     product_categories pc
     on p.category_id = pc."id" left join
     product_features pf
     on p.id = pf.product_id
where p.category_id in (58) and 
      ((pf.feature_category_id = 1 and pf.feature_option_id = 58) or 
       (pf.feature_category_id = 46 and pf.feature_option_id = 62)
      )
group by p.id
having count(distinct feature_category_id) = 2;

如果您需要select中的更多字段,您可以将其加入或包含在group by中。