2016-12-02 90 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