MySQL : double IN() statement

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

它是关于一位同时走两条路线的司机:马德里-巴塞罗那和巴塞罗那-马德里,但我的查询不起作用。

最佳答案

where in 是错误的方法,你要找的是 where exists

SELECT dname FROM driver WHERE exists
  ( select dcode from route inner join ride on route.rcode = ride.rcode
     where departure = 'Barcelona' and arrival = 'Madrid' and ride.dcode = driver.dcode
  )
  and exists
  ( select dcode from route inner join ride on route.rcode = ride.rcode
     where departure = 'Madrid' and arrival = 'Barcelona' and ride.dcode = driver.dcode
  )

或者,您也可以完全不使用子查询:

select dname 
  from driver d
    inner join ride r
      on d.dcode = r.dcode
    inner join route rr
      on r.rcode = rr.rcode
      and rr.departure = 'Barcelona'
      and rr.arrival = 'Madrid'
    inner join ride r2
      on d.dcode = r.dcode
    inner join route rr2
      on r2.rcode = rr2.rcode
      and rr2.departure = 'Madrid'
      and rr2.arrival = 'Barcelona';

demo here

关于MySQL : double IN() statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30008557/

相关文章:

mysql - 仅当两列中没有具有相同值的行(没有子查询)时,是否有一种有效的方法来插入?

sql - PL/pgSQL 函数似乎选择了错误的变量?

sql - RODBC:执行包含多个语句的查询

mysql - LEFT JOIN 查询 MYSQL 不工作

MySQL 5 : Trying to Generate Dynamic Sequence IDs as Stored Function or Stored Procedure

sql - oracle sql中用regexp转换数据

mysql - 在更新源表时插入一张表

php - Laravel Eloquent : Select where related table has x, 但从相关表中排除某些行

mysql - 使用 MySQL 触发器自动递增值

python - 通过python加载到MySQL的数据消失了