【问题标题】:MySQL select join where AND whereMySQL select join where AND where
【发布时间】:2011-06-28 09:49:36
【问题描述】:

我的数据库中有两个表:

产品

  • id(整数,主键)
  • 名称(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 是没有意义的,因为不会返回任何行。

【问题讨论】:

  • 我不明白你在追求什么?您愿意详细说明一些数据和示例吗?

标签: mysql join where-in relational-division


【解决方案1】:

这类问题称为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*/

【讨论】:

  • 这样就解决了问题。我想知道最后一行中的数字 3 代表什么。我得到了正确的结果:HAVING COUNT(DISTINCT ProductTags.tag_id) = 1 和任何大小的标签 id 数组:WHERE ProductTags.tag_id IN (1,2,3,4)
  • 您需要根据需要调整3。对于(1,2,3,4),您需要使用HAVING COUNT(DISTINCT ProductTags.tag_id) = 4,否则您将带回那些在4 个标签中具有任何3 个匹配标签的标签。
【解决方案2】:

您需要有一个 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 

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多