我的数据库中有两个表:

产品

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

产品标签

  • 产品 ID(整数)
  • 标签 ID(整数)

我想选择具有所有给定标签的产品。我试过:

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

有帮助吗?

解决方案

此类问题称为 关系划分

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

其他提示

您需要有一个分组依据/计数以确保所有内容都被考虑在内

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 

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top