[英]Mysql Many-to-many (AND Where) select
i have this database setup: 我有此数据库设置:
products 制品
tags 标签
product_tag product_tag
If have this records in my database 如果我的数据库中有此记录
How do i query to get the products that have tag_id 1 AND 2 (it must by products with tag_id 1 AND 2) in this example: "Product A" and "Product C" 在此示例中,如何查询具有tag_id 1和2的产品(必须由具有tag_id 1和2的产品组成):“产品A”和“产品C”
SELECT *
FROM products
WHERE id IN (
SELECT product_id
FROM product_tag
GROUP BY product_id
HAVING GROUP_CONCAT(tag_id) = '1,2'
)
Use this 用这个
SELECT P.id
FROM products P
INNER JOIN products_tags PT ON PT.product_id = P.id
WHERE PT.tag_id IN (1,2)
GROUP BY P.id
HAVING COUNT(PT.*) = 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.