MySQL Select ID's which occur on different rows with multiple specific values for a column

前端 未结 5 832
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 20:21

I\'m trying to select items from an associative table that have satisfy two or more values of the same field, sounds confusing, let me explain.

+------------         


        
5条回答
  •  囚心锁ツ
    2020-12-16 21:00

    Your expression in a WHERE clause works against a single row of the joined result set. That's why WHERE category_id = 201 AND category_id = 202 doesn't work -- because it can't be two values on a single row.

    So you need some way to join two rows from the table into one row of the result set. You can do this with a self-join:

    SELECT c1.item_id
    FROM item_category AS c1
    INNER JOIN item_category AS c2 ON c1.item_id = c2.item_id
    WHERE c1.category_id = 201 AND c2.category_id = 202
    

    This technique is hard to scale up when you want to search for three, four, five or more values, because it requires N-1 joins to match N values.

    So another method is to use GROUP BY:

    SELECT c.item_id, COUNT(*) AS cat_count
    FROM item_category AS c
    WHERE c.category_id IN (201,202)
    GROUP BY c.item_id
    HAVING cat_count = 2
    

    Both techniques are okay, and work better in different circumstances.

提交回复
热议问题