MySQL AND或AND的多对多条件 [英] MySQL Many-To-Many condition which combine AND/OR
本文介绍了MySQL AND或AND的多对多条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I have a problem with mysql query, it's complex problem which relates to Mysql join query for multiple "tags" (many-to-many relationship) that matches ALL tags?
所以我有经典的MN表架构:
So I have classic MN table schema:
Item
1 | Item1
2 | Item2
...
Category
1 | Category1
2 | Category2
3 | Category3
4 | Category4
...
Item_has_category
1 | 1
...
问题是-如何获得行,其中 item 具有 Category1 OR Category2 AND Category3 ?
And question is - How can I get rows, where item has Category1 OR Category2 AND Category3?
它用于某些复杂的过滤器,并且某些类别具有特殊的组,必须与 AND 一起使用.
It is for some complex filter and some categories has a special group, which must be with AND.
我想我必须将HAVING与DISTINCT (链接到顶部的其他问题)结合起来,但是我不确定如何.
I suppose that I must combine HAVING with DISTINCT (link to another questions at top), but I'm not sure how.
推荐答案
此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
这篇关于MySQL AND或AND的多对多条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文