我有三个复选框和一个仅显示交叉点的附加选项
复选框
绿色
可持续的
社会的
还有一个复选框,上面写着:check to show intersection
因此,当有人选择绿色时,他们需要看到所有绿色产品,如果他们选择绿色和社交,他们将看到所有附加了绿色标签或社交标签的产品,这可以简单地使用where product\u category\u id in(1,11)等等来完成。
现在,当有人选中绿色和社会和附加复选框,以显示只有交叉口,我只想显示的产品已明确分配了两个标签。i、 只是那些既有绿色标签又有社会标签的人,而忽略了其他的。
从下表的绿色和社会,它应该返回
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;
1条答案
按热度按时间kupeojn61#
虽然我可能会在表示层中执行此操作,但您需要的逻辑如下:
...GROUP BY ... HAVING COUNT(DISTINCT ...) = n
哪里:distinct是可选的,但不会造成伤害
和
n等于()中的参数数