I am having problems with SQL query. My diagram describes the relationship between many articles in the articles table and categories of the categories table β with the staging table article_category , which has the id , article_id and category_id fields.
I want to select all articles in which there are only categories with id 1 and 2 . Unfortunately, this query will also select any articles that have these categories in addition to others.
For example, this is an example of output from SQL ( with categories shown for descriptive purposes ). You can see that although the query selected an article with ID 10 , she also selected an article with ID 11 , despite having one additional category.
+-------+------------+ | id | categories | +-------+------------+ | 10 | 1,2 | | 11 | 1,2,3 | +-------+------------+
This is the result that I want to achieve from the selection of articles with categories 1 and 2 .
+-------+------------+ | id | categories | +-------+------------+ | 10 | 1,2 | +-------+------------+
Similarly, this is the result that I want to achieve from the selection of articles with categories 1 , 2 and 3 .
+-------+------------+ | id | categories | +-------+------------+ | 11 | 1,2,3 | +-------+------------+
This is the SQL I wrote. What am I missing to achieve the above?
SELECT articles.id FROM articles WHERE EXISTS ( SELECT 1 FROM article_category WHERE articles.id = article_id AND category_id IN (1,2) GROUP BY article_id )
Many thanks!
sql mysql many-to-many
user2406944
source share