简体   繁体   English

如何将此 SQL 查询转换为使用 GROUP BY 和 HAVING 查询?

[英]How to transform this SQL query to query with GROUP BY and HAVING?

There're products , products_filters , filters_values tables in DB.数据库中有productsproducts_filtersfilters_values表。
products_filters references to products table via product_id column which is a foreign key. products_filters通过作为外键的 product_id 列对产品表的引用。
Also products_filters references to filters_values table via filter_value_id column which is also a foreign key products_filters还通过 filter_value_id 列对filters_values表的引用,该列也是外键

When user selects filters, SQL query which extracts all ids of suitable products is formed.当用户选择过滤器时,会形成 SQL 查询,该查询提取合适产品的所有 id。

For example, chosen filters are:例如,选择的过滤器是:
Sex: Male, Female性别:男、女
Brand: Brand1, Brand2, Brand3品牌:品牌1、品牌2、品牌3

How it should work:它应该如何工作:
It needs to select all products which have filter Sex set to Male OR Female AND filter Brand set to Brand1 OR Brand2 OR Brand3.它需要 select 所有过滤器性别设置为男性或女性并且过滤器品牌设置为品牌 1 或品牌 2 或品牌 3 的产品。 But products having matching only in one of the chosen filter category either Sex or Brand, must not be selected.但是,不得选择仅在所选过滤类别之一中匹配的产品,无论是性别还是品牌。 It necessiraly to have matching in all selected categories.它必须在所有选定的类别中进行匹配。
I think SQL should look like this:我认为 SQL 应该是这样的:

SELECT product_id FROM products_filters WHERE 
(filter_value_id = 1 OR filter_value_id = 2) 
AND 
(filter_value_id = 3 OR filter_value_id = 4 OR filter_value_id = 5)

Where 1 is Male, 2 is Female, 3 is Brand1, 4 is Brand2, 5 is Brand3.其中 1 是男性,2 是女性,3 是品牌 1,4 是品牌 2,5 是品牌 3。

But this query doesn't work.但是这个查询不起作用。

In my previous question I was answered that GROUP BY and HAVING may help.在我之前的问题中,我回答说 GROUP BY 和 HAVING 可能会有所帮助。

Q: How can I transform SQL above with GROUP BY and HAVING?问:如何使用 GROUP BY 和 HAVING 转换上面的 SQL?

Given给定

    drop table if exists t;
    create table t(id int ,gender varchar(1), brand varchar(1));
    
    insert into t values
    (1,'m',1),(1,'f',2),(1,'m',3),(2,'f',1),(2,'f',2),(2,'f',3),
    (3,'m',1),(4,'f',2);

Correlated sub queries with distinct具有不同的相关子查询

    select distinct id
    from t
    where
             (select count(distinct gender) from t t1 where gender in('m','f') and t1.id = t.id) = 2 and
             (select count(distinct brand)  from t t1 where brand in(1,2,3) and t1.id = t.id) = 3
    ;

+------+
| id   |
+------+
|    1 |
+------+
1 row in set (0.002 sec)
SELECT product_id
    FROM products_filters AS f1
    JOIN products_filters AS f2  USING(product_id)
    WHERE f1.filter_value_id IN (1,2)
      AND f2.filter_value_id IN (3,4,5)

(I don't think GROUP BY...HAVING COUNT(*) = 2 is reasonable for this case.) (我不认为GROUP BY...HAVING COUNT(*) = 2对于这种情况是合理的。)

(The EAV schema design is a pain to deal with.) (EAV 模式设计很难处理。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM