问题
I have three tables in my database:
Products
- id (int, primary key)
- name (varchar)
Tags
- id (int, primary key)
- name (varchar)
ProductTags
- product_id (int)
- tag_id (int)
I'm doing SQL query to select products with assigned tags with given id's:
SELECT * FROM Products
JOIN ProductTags ON Products.id = ProductTags.product_id
WHERE ProductTags.tag_id IN (1,2,3)
GROUP BY Products.id
I can either select products without assigned tags with given id's:
SELECT * FROM Products
JOIN ProductTags ON Products.id = ProductTags.product_id
WHERE ProductTags.tag_id NOT IN (4,5,6)
GROUP BY Products.id
How could I combine that queries to select products having given tags, but not having other tags? I've tried to achieve this that way:
SELECT * FROM Products
JOIN ProductTags ON Products.id = ProductTags.product_id
WHERE ProductTags.tag_id IN (1,2,3)
AND ProductTags.tag_id NOT IN (4,5,6)
GROUP BY Products.id
But it's not working obviously, giving me products with tags (1,2,3), no matter they has tags (4,5,6) assigned or not. Is this possible to solve this problem using one query?
回答1:
Use a subquery to filter out the list of products that contain unwanted tags:
SELECT * FROM Products
JOIN ProductTags ON Products.id = ProductTags.product_id
WHERE ProductTags.tag_id IN (1,2,3)
AND Products.id NOT IN (SELECT product_id FROM ProductTags WHERE tag_id IN (4,5,6))
GROUP BY Products.id
来源:https://stackoverflow.com/questions/5016257/mysql-select-where-in-but-not-in-with-join