SQL嵌套查询(不存在)

时间:2013-05-02 15:33:40

标签: sql nested-queries

我有一个名为train的表,其中包含列号,arrival_station,depart_station

我填写了这个,并希望找到只为爱丁堡服务的火车(即所有 从火车站出发的火车只抵达爱丁堡) 我想使用嵌套查询并使用not exists运算符。

到目前为止,我已经尝试过..

SELECT depart_station
FROM train
WHERE arrive_station = "edinburgh" 
  AND NOT EXISTS
  (
    SELECT arrive_station
    FROM train
    WHERE arrive_station != "edinburgh"
  );

5 个答案:

答案 0 :(得分:4)

您需要以某种方式将嵌套查询与外部查询相关联,因此,如果编号是列号,则您需要在表中添加别名并添加AND t1.number = t2.number

SELECT  depart_station
FROM    train t1
WHERE   arrive_station = "edinburgh" 
AND     NOT EXISTS
        (
            SELECT  arrive_station
            FROM    train t2
            WHERE   t2.arrive_station != "edinburgh"
            AND     t1.number = t2.number
        );

答案 1 :(得分:1)

为什么需要使用exists运算符?当然,OR就足够了:

select *
from train
where depart_station = 'Edinburgh' or arrive_station = 'Edinburgh';

答案 2 :(得分:0)

如果我理解你的问题,你只对到达爱丁堡的任何火车路线感兴趣。所以这样做:

SELECT * FROM train WHERE arrive_station = "Edinburgh"

将此与“不存在”结合使用'表达式,创建一个其他路由表,是多余的;放下那部分。

答案 3 :(得分:0)

尝试,

SELECT depart_station
FROM train
WHERE arrive_station = "edinburgh" 
AND depart_station NOT IN (
    SELECT depart_station
    FROM train
    WHERE arrive_station != "edinburgh" 
)

检查this SQLFiddle

答案 4 :(得分:0)

SELECT  depart_station
FROM    train t1
WHERE   arrive_station = "edinburgh" 
AND     NOT EXISTS
        (
            SELECT  arrive_station
            FROM    train t2
            WHERE   t2.arrive_station != "edinburgh"
            AND     t1.number = t2.number
        );

查询中存在非常惊人的逻辑。它可以解决为:

select depart_station from train order by depart_station

但我有一个逻辑,这也解决了我的问题。我的问题有点不同,但无论如何,这确实提供了一个信号。