MySQL 选择连接 where AND where
我的数据库中有两个表:
Products
- id (int, Primary key)
- name (varchar)
ProductTags
- Product_id (int)
- tag_id (int)
我想选择具有所有给定的标签。我尝试过:
SELECT
*
FROM
Products
JOIN ProductTags ON Products.id = ProductTags.product_id
WHERE
ProductTags.tag_id IN (1, 2, 3)
GROUP BY
Products.id
但它为我提供了具有任何给定标签的产品,而不是具有所有给定标签的产品。编写 WHERE tag_id = 1 AND tag_id = 2
是没有意义的,因为不会返回任何行。
I have two tables in my database:
Products
- id (int, primary key)
- name (varchar)
ProductTags
- product_id (int)
- tag_id (int)
I would like to select products having all given tags. I tried:
SELECT
*
FROM
Products
JOIN ProductTags ON Products.id = ProductTags.product_id
WHERE
ProductTags.tag_id IN (1, 2, 3)
GROUP BY
Products.id
But it gives me products having any of given tags, instead of having all given tags. Writing WHERE tag_id = 1 AND tag_id = 2
is pointless, because no rows will be returned.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此类问题称为 关系划分
This type of problem is known as relational division
您需要有一个分组依据/计数以确保所有内容都被考虑在内
you need to have a group by / count to ensure all are accounted for
MySQL
WHERE fieldname IN (1,2,3)
本质上是WHERE fieldname = 1 OR fieldname = 2 OR fieldname = 3
的简写。因此,如果您无法使用WHERE ... IN
获得所需的功能,请尝试切换到OR
。如果仍然没有给您想要的结果,那么也许WHERE ... IN
不是您需要使用的函数。The MySQL
WHERE fieldname IN (1,2,3)
is essentially shorthand forWHERE fieldname = 1 OR fieldname = 2 OR fieldname = 3
. So if you aren't getting the desired functionality withWHERE ... IN
then try switching toOR
s. If that still doesn't give you the results you want, then perhapsWHERE ... IN
is not the function you need to use.