Вопрос

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?

Это было полезно?

Решение

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
)

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top