driver [ dcode, dname ]
route [ rcode, departure,arrival ]
ride [ dcode, rcode ]
SELECT dname FROM driver WHERE dcode IN (
SELECT dcode FROM ride WHERE rcode IN (
SELECT rcode FROM route WHERE departure = 'Barcelona' AND arrival = 'Madrid'
) AND
rcode IN (
SELECT rcode FROM route WHERE departure = 'Madrid' AND arrival= 'Barcelona'
)
);
关于制作两条路线的司机:马德里 - 巴塞罗那和巴塞罗那 - 马德里,但我的查询不起作用。
答案 0 :(得分:2)
你的内部查询(第二个lvl)没有返回任何结果,因为可能不存在rcode
,它可以在第一个子集(B-> M)中,而在第二个子集中(M-> B) 。请试试这个:
SELECT dname FROM driver WHERE dcode in
(SELECT dcode
FROM ride JOIN route
ON (ride.rcode=route.rcode)
WHERE route.departure = 'Barcelona' AND route.arrival = 'Madrid'
) AND dcode in (
SELECT dcode
FROM ride JOIN route
ON (ride.rcode=route.rcode)
WHERE route.departure = 'Madrid' AND route.arrival = 'Barcelona'
)
答案 1 :(得分:1)
我认为您采取的方法是:
dcode
司机。我们称之为 Set1 。dcode
。我们称之为 Set2 。dname
同时包含 Set1 和 Set2 的驱动程序获取dcode
。您对 Set1 的查询是:
SELECT dcode FROM ride WHERE rcode IN (
SELECT rcode FROM route WHERE departure = 'Barcelona' AND arrival = 'Madrid'
)
在同一行, Set2 的查询将是:
SELECT dcode FROM ride WHERE rcode IN (
SELECT rcode FROM route WHERE departure = 'Madrid' AND arrival = 'Barcelona'
)
最后,您需要{/ 1}} Set1 & Set2 。这将转换为查询:
dcode
在您的查询中,您不是在两组中查找SELECT dname FROM driver WHERE
dcode IN (
SELECT dcode FROM ride WHERE rcode IN (
SELECT rcode FROM route WHERE departure = 'Barcelona' AND arrival = 'Madrid'
)
)
AND
dcode IN (
SELECT dcode FROM ride WHERE rcode IN (
SELECT rcode FROM route WHERE departure = 'Madrid' AND arrival = 'Barcelona'
)
)
,而是在两组中查找dcode
。
改进建议:对于获取rcode
集的查询,您可以使用内部联接而不是使用嵌套查询。例:
dcode
答案 2 :(得分:0)
不应该是
SELECT dname FROM driver WHERE dcode IN (
SELECT dcode FROM ride WHERE rcode IN (
SELECT rcode FROM route WHERE departure = 'Barcelona' AND arrival =
'Madrid'
) OR
rcode IN (
SELECT rcode FROM route WHERE departure = 'Madrid' AND arrival= 'Barcelona'
)
);
OR
代替AND
...?