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.
+-----------------------+
| item_id | category_id |
+-----------------------+
| 1 | 200 |
| 1 | 201 |
| 1 | 202 |
| 2 | 201 |
| 2 | 202 |
| 3 | 202 |
| 3 | 203 |
| 4 | 201 |
| 4 | 207 |
+-----------------------+
In the table, I want to be able to select only items which are in the categories that I pass. So for example, if I pass category IDs of 201 and 202, I would want only items that are in BOTH categories (they can have other categories but need to be in at least the categories I'm querying), so in this case, I would want items 1 and 2 only since they are the only ones that are in categories 201 and 202.
My initial SQL statement was something like
SELECT * FROM item_category WHERE category_id = 201 AND category_id = 202;
But obviously that won't work.
SELECT * FROM item_category WHERE category_id = 201 OR category_id = 202;
The above query also won't work because it'll return items 4 and 3 as well.
So how would I go about only selecting items that have to at least be in both categories?
Keep in mind that I might be passing more than 2 category IDs.
Thank you for your help.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…