2013-03-18 137 views
4

我試圖寫一個查詢,確定哪些城市我不能直接從一個城市飛往倫敦。鑑於模式:試圖找到所有沒有直飛城市的城市(PostgreSQL)

城市:

| c_id | city_name | 

航班:

| f_id | departure_city_id | destination_city_id | 

目前我的查詢返回相反的,也就是說,它返回其中有來自倫敦

直達航班的城市
SELECT c2.city_name as "City" 
FROM flights AS f 
JOIN cities AS c2 ON f.destination_city_id != c2.c_id 
JOIN cities AS c ON c.c_id = c.c_id 
WHERE c.city_name = 'London' 
AND c.c_id != c2.c_id 
AND f.departure_city_id = c.c_id; 

我原以爲這會很容易改變它得到我想要的。 我以爲改變第三行

JOIN cities AS c2 ON f.destination_city_id = c2.c_id 

會做的伎倆,但事實並非如此。任何幫助?

回答

0

試着這麼做:

SELECT * 
FROM cities c 
WHERE c.c_id NOT IN 
(SELECT f.destination_city_id 
FROM flights f 
JOIN cities c2 ON f.departure_city_id = c.c_id 
WHERE c2.city_name = 'London') 
1

城市,我不能從一個城市飛到直接,說倫敦。

含義一個可以從倫敦飛到那裏,只是沒有直接。所以JOIN(不LEFT JOIN)通過destination_city_idcityflight

SELECT DISTINCT c.city_name 
FROM cities c 
JOIN flights f ON f.destination_city_id = c.c_id 
JOIN cities c2 ON c2.c_id = f.departure_city_id 
WHERE c2.city_name <> 'London'; 

然後,我只需要排除從倫敦始發航班,適用DISTINCT獲得獨特的城市名稱,我們正在做。

更復雜這個問題的解釋是:
「的城市,你可以從倫敦飛,只是沒有直接」
但由於這看起來像功課基本我不認爲他們會期望來自你的遞歸查詢