Mysql 多对多(以及在哪里)select
Mysql Many-to-many (AND Where) select
我有这个数据库设置:
产品
- id
- [字段...]
标签
- id
- [字段...]
product_tag
- id
- product_id
- tag_id
如果我的数据库中有这条记录
- 产品
- 产品 A [id: 1]
- 产品 B [id: 2]
- 产品 C [id: 3]
- 标签
- 标签 A [id: 1]
- 标签 B [id: 2]
- 标签 C [id: 3]
- Produc_Tag
- [product_id: 1, tag_id: 1]
- [product_id: 1, tag_id: 2]
- [product_id: 2, tag_id: 1]
- [product_id: 2, tag_id: 3]
- [product_id: 3, tag_id: 1]
- [product_id: 3, tag_id: 2]
我如何查询得到具有 tag_id 1 和 2 的产品(它必须通过具有 tag_id 1 和 2 的产品)
在此示例中:"Product A" 和 "Product C"
SELECT *
FROM products
WHERE id IN (
SELECT product_id
FROM product_tag
GROUP BY product_id
HAVING GROUP_CONCAT(tag_id) = '1,2'
)
使用这个
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
我有这个数据库设置:
产品
- id
- [字段...]
标签
- id
- [字段...]
product_tag
- id
- product_id
- tag_id
如果我的数据库中有这条记录
- 产品
- 产品 A [id: 1]
- 产品 B [id: 2]
- 产品 C [id: 3]
- 标签
- 标签 A [id: 1]
- 标签 B [id: 2]
- 标签 C [id: 3]
- Produc_Tag
- [product_id: 1, tag_id: 1]
- [product_id: 1, tag_id: 2]
- [product_id: 2, tag_id: 1]
- [product_id: 2, tag_id: 3]
- [product_id: 3, tag_id: 1]
- [product_id: 3, tag_id: 2]
我如何查询得到具有 tag_id 1 和 2 的产品(它必须通过具有 tag_id 1 和 2 的产品) 在此示例中:"Product A" 和 "Product C"
SELECT *
FROM products
WHERE id IN (
SELECT product_id
FROM product_tag
GROUP BY product_id
HAVING GROUP_CONCAT(tag_id) = '1,2'
)
使用这个
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