2016-04-06 29 views
1

表一如何從那裏柱不在另一個表中存在

id city 
1 koronadal 
2 cebu 
3 manila 

表B表中選擇

id city 
1 cebu 

預計輸出繼電器:

id city 
1 koronadal 
3 manila 

這裏是我的查詢:

Select a.id, a.city from tablea a left join tableb b on a.city = b.city 

我得到了錯誤的輸出..請幫我..

回答

0

你是對的!現在你只需要過濾那些誰匹配:

Select a.id, a.city 
from tablea a 
left join tableb b 
on a.city = b.city 
WHERE b.id is null 

LEFT JOINING當沒有右表的匹配連接條件的,左邊的表,在這種情況下,表A仍將被選中,所有的數據,在這種情況下,tableB將是NULL。所以你所要做的就是在B表上搜索空值。

另一種方法是使用IN()

SELECT * FROM TableA a 
WHERE a.city NOT IN(SELECT city FROM TableB) 

而另一種方式是EXISTS()

SELECT * FROM TableA a 
WHERE NOT EXISTS(SELECT 1 FROM TableB b 
       WHERE a.city = b.city) 
+0

非常感謝你的幫助.. – redbull

相關問題