MySQL选择连接在何处AND

时间:2011-02-16 14:33:34

标签: mysql join where-in relational-division

我的数据库中有两个表:

产品

  • 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毫无意义,因为不会返回任何行。

3 个答案:

答案 0 :(得分:16)

此类问题称为relational division

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*/

答案 1 :(得分:0)

你需要有一个按/计数的组来确保所有的都被计算在内

select Products.*
  from Products 
         join ( SELECT Product_ID
                  FROM ProductTags
                  where ProductTags.tag_id IN (1,2,3)
                  GROUP BY Products.id
                  having count( distinct tag_id ) = 3 ) PreQuery
        on ON Products.id = PreQuery.product_id 

答案 2 :(得分:0)

MySQL WHERE fieldname IN (1,2,3)本质上是WHERE fieldname = 1 OR fieldname = 2 OR fieldname = 3的简写。因此,如果您未使用WHERE ... IN获得所需的功能,请尝试切换到OR。如果仍然无法提供您想要的结果,那么WHERE ... IN可能不是您需要使用的功能。