结合AND / OR的MySQL多对多条件
作者:互联网
我的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
...
问题是-如何获得行,其中项目具有Category1或Category2 AND Category3?
它用于某些复杂的过滤器,并且某些类别具有特殊的组,该组必须与AND一起使用.
我想我必须将HAVING与DISTINCT结合起来(链接到顶部的另一个问题),但是我不确定如何结合.
解决方法:
该小组将工作:
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
标签:many-to-many,sql,mysql 来源: https://codeday.me/bug/20191130/2077153.html