如何在SQL中正确使用EXISTS

时间:2016-03-15 22:17:12

标签: sql exists

我遇到了家庭作业的问题,我必须使用EXISTS过滤日期为2016-07-23的结果,但它总是会返回所有内容。我可以使用内部连接来使用它,所以我必须使用EXISTS不正确,但我无法弄清楚我出错的地方。我将在下面包含我的代码,我在SQLquery数据库中工作。

select 
    c.last_name, t.trip_name, t.start_location
from 
    customer c
inner join 
    reservation r on c.customer_num = r.customer_num
inner join 
    trip t on t.trip_ID = r.trip_id
where 
    exists (select r.trip_date 
            from reservation r
            where r.trip_date = '2016-07-23'); 

3 个答案:

答案 0 :(得分:1)

您需要将exists语句中的子查询连接到外部查询,否则一切都将返回,因为exists语句将始终求值为true:

select 
    c.last_name, t.trip_name, t.start_location
from 
    customer c
inner join 
    reservation r on c.customer_num = r.customer_num
inner join 
    trip t on t.trip_ID = r.trip_id
where 
    exists (select r2.trip_date 
            from reservation r2
            where
             r2.customer_num = c.customer_num --connect to current customer
             and r2.trip_date = '2016-07-23'); 

这将为您提供所有在7/23/16预订的客户。您可能需要通过将子查询添加到where子句来将子查询连接到trip表:

and r2.trip_id = t.trip_id

这可能过于狭窄的过滤器(由于我不知道您的数据,因此无法确定)。

答案 1 :(得分:0)

您的子查询结果总是在同一行,因为有人指出您应该将子查询引用到主查询:

select c.last_name, t.trip_name, t.start_location
from customer c
inner join reservation r
on c.customer_num = r.customer_num
inner join trip t
on t.trip_ID = r.trip_id
where exists (
select ri.trip_date 
from reservation ri
where ri.trip_date = r.trip_date); 

我猜想你想以这种尴尬的方式加入预订回到预订状态。如果您想要加入其他日期字段,只需更改即可。

答案 2 :(得分:0)

正如已经指出的那样,您需要连接到外部表来过滤外部查询中的记录。您的查询应该如下所示:

select c.last_name, t.trip_name, t.start_location
from customer c
inner join reservation r
on c.customer_num = r.customer_num
inner join trip t
on t.trip_ID = r.trip_id
where exists (
select ri.trip_date 
from reservation ri
where r.customner_num = ri.customer_num
AND ri.trip_date = '2016-07-23');