我的 mysql 查询有问题,这是一个与 Mysql join query for multiple "tags" (many-to-many relationship) that matches ALL tags? 相关的复杂问题
所以我有经典的 MN 表模式:
Item
1 | Item1
2 | Item2
...
Category
1 | Category1
2 | Category2
3 | Category3
4 | Category4
...
Item_has_category
1 | 1
...
问题是 - 如何获取行,其中 item 具有 Category1 OR Category2 和类别 3?
针对一些复杂的filter,一些categories有一个特殊的分组,必须用AND。
我想我必须结合 HAVING 和 DISTINCT (链接到顶部的另一个问题),但我不确定如何结合。
最佳答案
这个 group by
可以工作:
select ItemId
from Item_has_category
group by
ItemId
having sum(case when CategoryId = 1 then 1 end) = 1
or sum(case when CategoryId = 2 then 1 end) = 1
andsum(case when CategoryId = 3 then 1 end) = 1
关于结合 AND/OR 的 MySQL 多对多条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11829617/