MySQL:双重IN()语句

时间:2015-05-02 23:18:55

标签: mysql sql

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'
   )
);

关于制作两条路线的司机:马德里 - 巴塞罗那和巴塞罗那 - 马德里,但我的查询不起作用。

3 个答案:

答案 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)

我认为您采取的方法是:

  1. 获取巴塞罗那到马德里的路线上的dcode司机。我们称之为 Set1
  2. 获取马德里到巴塞罗那的司机dcode。我们称之为 Set2
  3. 最后,为dname同时包含 Set1 Set2 的驱动程序获取dcode
  4. 您对 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 ...?