假设我有一张桌子,列出了各种玩具及其所用的电池类型:
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;
结果看起来是正确的,但我很好奇,如果我错过了什么。
答案 0 :(得分: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
答案 1 :(得分:1)
我认为您可以在没有full
的情况下使用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;