MySQL Many-To-Many condition which combine AND/OR

戏子无情 提交于 2019-12-12 16:17:46

问题


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?

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
...

And question is - How can I get rows, where item has Category1 OR Category2 AND Category3?

It is for some complex filter and some categories has a special group, which must be with AND.

I suppose that I must combine HAVING with DISTINCT (link to another questions at top), but I'm not sure how.


回答1:


This group by would work:

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 



回答2:


select * from Item i
  inner join Item_has_category ic on i.ID = ic.I_ID
  where (ic.C_ID = 1 OR ic.C_ID = 2) AND ic.C_ID = 3



回答3:


Try this::

Item

Category

Item_has_category

Select * from 
itemcategorymapping icm 
inner join item i on (icm.itemID=i.itemId)
inner join category c on (icm.catId=c.catId)
group by icm.itemId having ((icm.catId=CAT1 or icm.catId=Cat2) AND icm.catID=cat3)



回答4:


The idea from Andomar answer is very good and it was breakthrough for me. I propose the upgraded version. It is more elegant and universal way to work with tags groups AND/OR logic. It don't needs OR operators, have compact, self-explainable view and easy to generate syntax.

SELECT  ItemId
FROM    Item_has_category
GROUP BY
        ItemId
HAVING      SUM(CASE WHEN CategoryId IN (1,2) THEN 1 END) > 0
        AND SUM(CASE WHEN CategoryId IN (3)   THEN 1 END) > 0
        AND SUM(...             


来源:https://stackoverflow.com/questions/11829617/mysql-many-to-many-condition-which-combine-and-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!