mysql joins - how to find all children that belongs to ALL parents

怎甘沉沦 提交于 2019-12-12 02:33:16

问题


I have three mysql tables

items
===========
id    title

items_in_categories
============================
id    item_id    category_id

categories
===========
id    title

I want to find all the items that belong to ALL the stated categories. Not any one category, but ALL categories

Eg, if I want to search all the items that belongs to category id 3 and 5

the no. of possible categories to be searched can go up to as many as 20.

Eg, I want to get all the items that belongs to category id 1, 2, 3, 4, 5, 6, .... and 20

I would like to use as simple a way as possible.

I have tried AND and a nested NOT EXISTS as stated in the mysql manual.

Nothing worked.

UPDATE: I came up with this.

select * from 
    (select count(*) as counter, item_id from items_in_categories 
        where category_id in (3, 5) group by item_id)getall 
where counter = 2

Is there a better way?


回答1:


I know this can be prettied up and put into one query (You could nest the category count within the having instead of as a separate query...I just think this is more readable), but here is my shot at this:

DECLARE @CategoryCount INT;

SELECT @CategoryCount = COUNT(DISTINCT id) AS CategoryCount
FROM categories
WHERE category_id IN (3,5);

SELECT *
FROM items
WHERE item_id IN 
(
    SELECT item_id
    FROM items_in_categories
    WHERE items_in_categories.category_id IN (3,5)
    GROUP BY item_id
    HAVING COUNT(DISTINCT category_id) = @CategoryCount
)



回答2:


You can accomplish that using the "IN" clause like this:

SELECT i.* 
FROM items i
WHERE i.id IN (SELECT item_id from items_in_categories where category_id IN (3,5))



回答3:


select * from items i , items_in_categories iic, categories c where i.id = iic.item_id and iic.category_id = c.id and c.id in(select * from category where id in(3,5))

if you are not getting distinct item from above query, you can add DISTINCT on item's id.



来源:https://stackoverflow.com/questions/9883796/mysql-joins-how-to-find-all-children-that-belongs-to-all-parents

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