【问题标题】:SQL Get all filtered itemsSQL 获取所有过滤的项目
【发布时间】:2015-06-08 11:56:44
【问题描述】:

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

例如。以下是该帮助表中的示例插入:

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 个或更多该类型的 where 子句,则返回 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))

【问题讨论】:

  • 这适用于哪个 RDBMS?请添加标签以指定您使用的是mysqlpostgresqlsql-serveroracle 还是db2 - 或其他完全不同的东西。

标签: sql postgresql laravel filter


【解决方案1】:

您可以使用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 中。

【讨论】:

  • 这应该有助于弄清楚如何在 Laravel 中做到这一点,因为他的数据库查询构建器中的方法无法采用这种形式的数据?
猜你喜欢
  • 1970-01-01
  • 2021-05-03
  • 2021-11-19
  • 1970-01-01
  • 2020-11-02
  • 2023-02-23
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多