2016-12-02 88 views
0

所以有3个表SQL SELECT所有记录所有

1通勤详细

2预订

3飞行

通勤

+----+------+ 
| id | name | 
+----+------+ 
| 1 | A | 
| 2 | B | 
| 3 | C | 
+----+------+ 

预订

+----+-------+ 
| id |flight | 
+----+-------+ 
| 1 | 101 | 
| 1 | 102 | 
| 1 | 103 | 
| 2 | 101 | 
| 3 | 104 | 
| 2 | 105 | 
+----+-------+ 

飞行

+--------+------+ 
| flight | late | 
+--------+------+ 
| 101 | 80 | 
| 102 | 80 | 
| 103 | 80 | 
| 104 | 10 | 
| 105 | 10 | 
+--------+------+ 

表1中包含passnger ID和名称

表2包含通勤ID和飞行ID

表3中包含航班号和分多少是

现在我想找出所有航班迟到或迟到50分钟的passanger的名字

所以输出将是A因为101 102和103是晚80分钟

B因为101是80分钟迟,但105是10分钟晚(不是所有的B的航班晚50)

所以我的做法是

select name from passanger,booking where passanger.id=booking.id and booking.flight = ALL (select flight.flight from flight where flight.late>50) 

不能得到所需的输出。

回答

1

您可以按名称进行分组,并检查一个乘客的所有航班是否晚于having条件。

select p.name 
from passanger p 
join booking b on p.id=b.id 
join flight f on f.flight = b.flight 
group by p.name 
having count(*) = count(case when f.late>50 then f.flight end) 
+0

请解释此行**有COUNT(*)=计数(例如,当f.late> 50,然后f.flight结束时)** – codenut

+0

例如,对于乘客id 2,有2行......计数(*)= 2和计数(当f.late> 50然后f.flight结束)'将是1,因为他的航班中只有一个航班晚点50以上,另一排航班不符合条件,不会计算在内。所以条件失败(2!= 1)。对于乘客ID 1,count(*)= 3和count(当f.late> 50时f.flight结束时)= 3,所以你会在你的输出中得到那一行。 –

+0

好,非常感谢 – codenut

0

试试这个:

select name from passanger, booking 
where passanger.id = booking.id 
and booking.flight in (select flight.flight from flight 
         where flight.late > 50) 

select name from passanger, booking, flight 
where passanger.id = booking.id and booking.flight = flight.flight and flight.late > 50 

这将导致一个名字3倍和b的名字一次,但如果你想只有一个的实例和b结果,您可以使用select distinct name

+0

'booking'表是从'FROM' – RomanPerekhrest

+0

错过我补充说,但后来不小心删除了它,而编辑正确缩进,感谢您指出了:d –

0
select ps.name from passanger ps left join booking bk on (ps.id = bk.id) left join flight fl on (fl.flight = bk.flight) where late >50