我在这个网站的Q9上挣扎:http://sqlzoo.net/a1m.htm
这就是我现在所说的,即使我知道这是不对的
SELECT ID,
modle,
DOW,
TOD
FROM event x
WHERE modle = (SELECT modle
FROM event y
WHERE y.TOD = x.TOD)
以下是ER图的链接:sqlzoo.net/a1.htm
这样做的正确方法是什么?
答案 0 :(得分:3)
这个问题:
SELECT ID, modle, DOW, TOD
FROM event x
WHERE modle = (SELECT modle FROM event y WHERE y.TOD = x.TOD)
...子查询可以返回多行。对于这种情况,您希望使用IN
而不是等于:
SELECT ID, modle, DOW, TOD
FROM event x
WHERE modle IN (SELECT modle FROM event y WHERE y.TOD = x.TOD)
否则,您将需要使用聚合或过滤条件来确保始终从子查询返回单个记录。
我更喜欢使用ANSI-92 JOIN语法:
SELECT x.*
FROM EVENT x
JOIN EVENT y ON y.tod = x.tod
AND y.modle = 'co72010'
IN
SELECT x.*
FROM EVENT x
WHERE x.tod IN(SELECT y.tod
FROM EVENT y
WHERE y.modle = 'co72010')
EXISTS
SELECT x.*
FROM EVENT x
WHERE EXISTS(SELECT NULL
FROM EVENT y
WHERE y.modle = 'co72010'
AND y.tod = x.tod)
答案 1 :(得分:0)
您应该尝试使用两次相同的表连接。从:
开始
SELECT e2.id
FROM event AS e1, event AS e2
WHERE e1.modle = 'co72010'
AND …
我让你填补点。