MySQL select where in but not in with join

不问归期 提交于 2019-12-23 18:24:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!