1

假设我有一张表格,列出了各种玩具及其所用电池的类型:

toy_id   battery_id    battery_qty
     1            3              1
     2            2              4
     2            3              1
     3            1              1

我想构建一个查询,告诉我哪些玩具同时使用 2 型和 3 型电池(但也可能使用其他玩具)。在上面的示例中,即 toy_id 2。

我该如何编写这样的查询?

这是我到目前为止所拥有的,但看起来很混乱:

SELECT t1.toy_id,
    t1.battery_id b1, t2.battery_id b2,
    t1.battery_qty qty1, t2.battery_qty qty2
FROM toys t1
LEFT JOIN toys t2
    ON t1.toy_id = t2.toy_id
WHERE t1.battery_id = 2
    AND t2.battery_id = 3
HAVING q1 > 0
    AND q2 > 0
ORDER BY toy_id ASC;

结果看起来是正确的,但我很好奇我是否遗漏了什么。

4

2 回答 2

3

我认为这里真的不需要加入。您只需要计算记录的实例数,它等于您搜索的条件数。

SELECT  toy_ID
FROM    toys
WHERE   battery_ID IN (2,3)
GROUP BY toy_ID
HAVING COUNT(*) = 2

但是如果没有在每个 toy_id 的 battery_id 上定义唯一约束,DISTINCT则需要在该HAVING子句中。

SELECT  toy_ID
FROM    toys
WHERE   battery_ID IN (2,3)
GROUP BY toy_ID
HAVING COUNT(DISTINCT battery_ID) = 2
于 2012-11-29T01:58:53.167 回答
1

我认为您可以full不使用 join qty(假设您的表中的 battery_qty 始终 > 0)为:

  SELECT distinct t1.toy_id
  FROM toys t1
  JOIN toys t2
  ON t1.toy_id = t2.toy_id
  WHERE t1.battery_id = 2
    AND t2.battery_id = 3
  ORDER BY toy_id ASC;
于 2012-11-29T01:58:18.900 回答