Dar*_*ski 13 mysql join where-in relational-division
我的数据库中有两个表:
制品
ProductTags
我想选择具有所有给定标签的产品.我试过了:
SELECT
*
FROM
Products
JOIN ProductTags ON Products.id = ProductTags.product_id
WHERE
ProductTags.tag_id IN (1, 2, 3)
GROUP BY
Products.id
Run Code Online (Sandbox Code Playgroud)
但它给了我带有任何给定标签的产品,而不是所有给定的标签.写作WHERE tag_id = 1 AND tag_id = 2
毫无意义,因为不会返回任何行.
Mar*_*ith 20
这种类型的问题称为关系划分
SELECT Products.*
FROM Products
JOIN ProductTags ON Products.id = ProductTags.product_id
WHERE ProductTags.tag_id IN (1,2,3)
GROUP BY Products.id /*<--This is OK in MySQL other RDBMSs
would want the whole SELECT list*/
HAVING COUNT(DISTINCT ProductTags.tag_id) = 3 /*Assuming that there is a unique
constraint on product_id,tag_id you
don't need the DISTINCT*/
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
63992 次 |
最近记录: |