我有三个复选框和一个仅显示交叉点的附加选项
复选框
- 绿色
- 可持续发展
- 社交
另一个复选框显示:选中以显示交集
因此,当有人选择“绿色”时,他们需要查看所有绿色产品,如果他们选择“绿色”和“社交”,他们将看到所有附加了绿色标签或社交标签的产品,这可以使用 WHERE Product_category_id IN (1 ,11) 等等。
现在,当有人选中“绿色”和“社交”以及仅显示交叉点的附加复选框时,我只想显示分配了两个标签的产品。即只具有绿色和社会标签的那些,而忽略其余的。
从下表中绿色和社交它应该返回
id organisation_name
-----------------------------------------------
3221 Nederlandse Watershapsbank NV
如果有人选择绿色、可持续和社会以及相交选项,他们应该只会看到:
id organisation_name
--------------------------------
21 Uppsalahem AB
产品表
id issuer
-------------------------
1 1
11 1741
21 21
31 31
41 3221
51 51
组织结构表
id organisation_name
----------------------------------------
1 Nordic Investment Bank
21 Uppsalahem AB
31 Stangastaden
51 European Investment Bank
1741 Global Infrastructure Partners
3221 Nederlandse Watershapsbank NV
项目类别表
id product_id product_category_id
--------------------------------------------------
1 1 1
2 11 1
3 21 1
4 31 1
5 41 1
5 41 61
6 51 1
6 51 11
6 21 61
6 21 11
项目类别表
id product_category_name
--------------------------------------
1 Green
11 Sustainable
61 Social
SQL:
SELECT Products.id,
Organisation.organisation_name,
ProductCategory.product_category_id,
ProductCategory.product_id
FROM `Products`
LEFT JOIN `product_category` `ProductCategory` ON ProductCategory.product_id=Products.id
LEFT JOIN `organisation` `Organisation` ON Organisation.id=Products.issuer
LEFT JOIN `categories` `Categories` ON Categories.id=ProductCategory.product_category_id
WHERE `ProductCategory`.`product_category_id` IN (1, 11)
GROUP BY Products.id HAVING COUNT(*) = 2
ORDER BY Products.id ASC;
最佳答案
虽然我可能会在表示层中执行此操作,但您正在寻找的逻辑如下:
...GROUP BY ... HAVING COUNT(DISTINCT ...) = n
地点:
DISTINCT 是可选的,但不会造成任何损害
和
n 等于 IN() 中的参数数量
关于MySQL 选择与使用复选框选择的类别完全匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50718310/