I have table like this:
news_to_category
news_id | category_id |
---|---|
1 | 1 |
1 | 2 |
1 | 3 |
2 | 1 |
2 | 2 |
2 | 3 |
3 | 1 |
3 | 2 |
4 | 1 |
4 | 2 |
4 | 4 |
5 | 2 |
5 | 3 |
5 | 4 |
And now I need to get all news_id
containing category_id
equals 1
and 2
, so the result should be:
1, 2, 3, 4
(news 5
has 2
category, but doesn’t have 1
category)
How can I create SQL for this problem.
#mysql
I have tried SELECT * FROM news_to_category WHERE news_id IN (SELECT DISTINCT FROM news_to_category WHERE category_id = 1) AND news_id IN (SELECT DISTINCT FROM news_to_category WHERE category_id = 2)
2
Answers
Try this one:
SELECT * FROM news_to_category
WHERE category_id IN (1,2)
GROUPBY news_id
Common logical division:
If
(news_id, category_id)
is defined as UNIQUE then DISTINCT can be removed.