13

我的数据库中有两个表:

产品

  • id (int, 主键)
  • 名称(varchar)

产品标签

  • 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是没有意义的,因为不会返回任何行。

4

3 回答 3

21

这种类型的问题称为关系除法

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*/
于 2011-02-16T14:35:08.153 回答
0

MySQLWHERE fieldname IN (1,2,3)本质上是WHERE fieldname = 1 OR fieldname = 2 OR fieldname = 3. 因此,如果您没有获得所需的功能,请WHERE ... IN尝试切换到ORs。如果那仍然没有给您想要的结果,那么可能WHERE ... IN不是您需要使用的功能。

于 2011-02-16T14:40:41.037 回答
0

你需要有一个 group by / count 以确保所有的都被考虑在内

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 
于 2011-02-16T14:37:29.037 回答