使用外部加入的难度

时间:2017-10-08 09:10:14

标签: sql postgresql

我在使用外连接编写此问题的查询时遇到问题。我可以在没有外连接的情况下编写这个,但是它给了我一些外连接的困难时间。

问题:

  

对于'2018-01-01'上的每个航班,找到所有尚未预订的座位(使用外部联接)。对于每个未预留的座位,请显示航班号和座位号。

我有以下表格:

create table passenger ( 
    passenger_ID varchar ( 10 ) , 
    passenger_name varchar ( 30 ) , 
    passenger_city varchar ( 30 ) , 
    primary key ( passenger_ID ) ) ;

create table flight ( 
    flight_number varchar ( 10 ) , 
    departure_airport varchar ( 10), 
    arrival_airport varchar ( 10 ) , 
    primary key ( flight_number ) );

create table seat ( 
flight_number varchar ( 10 ),
seat_number varchar ( 10 ),
primary key(flight_number, seat_number),
foreign key(flight_number) references flight);

create table reservation(
    passenger_ID varchar (10),
                         flight_number varchar (10), 
                         seat_number varchar ( 10 ), 
                         day date ,
                         fare numeric(8,2),
primary key (flight_number, seat_number,day),
foreign key (flight_number, seat_number) references seat  ,
foreign key (passenger_ID) references passenger );

请看这个sql小提琴。我已经构建了架构。 [http://sqlfiddle.com/#!17/feaca/1

我现在的查询是:

Select distinct a.flight_number , a.seat_number
from 
seat a
left outer join 
reservation b
on 
a.flight_number = b.flight_number
and 
a.seat_number <> b.seat_number
where b.day = to_date('2017-10-01','YYYY-MM-DD') 
order by 1;

任何建议和帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

您想要在flight_number,seat_number以及给定日期上保持联接。然后,您可以过滤掉预订中没有相应行的行。

Select distinct s.flight_number , s.seat_number
from seat s
left outer join reservation r
    on r.flight_number = s.flight_number
    and r.seat_number = s.seat_number
    and r.day = to_date('2017-10-01','YYYY-MM-DD')
join (
    select distinct flight_number
    from reservation
    where day = to_date('2017-10-01','YYYY-MM-DD')
) r2 on s.flight_number = r2.flight_number
where r.day is null
order by 1;

或使用IN

Select distinct s.flight_number , s.seat_number
from seat s
left outer join reservation r
    on r.flight_number = s.flight_number
    and r.seat_number = s.seat_number
    and r.day = to_date('2017-10-01','YYYY-MM-DD')
where r.day is null
and s.flight_number in (
    select flight_number
    from reservation
    where day = to_date('2017-10-01','YYYY-MM-DD')
    )
order by 1;