2012-03-31 53 views
6

我有表1,all_countries,如下 -MySQL的內部聯接查詢來獲取記錄不存在於其他表

id | country 
------------------ 
1 | USA 
2 | China 
3 | India 
4 | France 
5 | UK 
6 | Australia 

我也有表2,supported_countries,因爲 -

id | country 
------------------ 
1 | USA 
2 | China 

現在我需要一個查詢結果,其中包括所有不支持的國家/地區的結果

因此,根據上面的示例,我應該得到

India 
France 
UK 
Australia 

我使用下面的查詢 - !

SELECT ac.country FROM all_countries交流INNER JOIN supported_countries鈧在sc.country_name = ac.country_name

它正常工作時,除supported_countries表爲空,它不顯示任何記錄。如何實現這個結果?

回答

24

一個LEFT JOIN將這樣做優雅;

SELECT a.* 
FROM all_countries a 
LEFT JOIN supported_countries s 
    ON a.country = s.country 
WHERE s.id IS NULL; 

演示here

+0

增加投票是明確格式化 - 它工作:) – Datadimension 2016-07-07 18:55:43

3

嘗試類似如下:

SELECT * FROM all_countries 
    WHERE country NOT IN (SELECT country FROM supported_countries) 
+0

這對我的偉大工程 - 不知道爲什麼答案沒工作... – thevoipman 2013-07-18 10:41:08

+3

子查詢通常[性能較低](http://stackoverflow.com/questions/3856164/sql-joins-vs-sql-subqueries-performance)比顯式連接。他們更容易閱讀,但不能很好地擴展。 – jonathanbruder 2014-03-03 22:55:49

1

SELECT ac.country FROM all_countries交流 LEFT JOIN supported_countries鈧在 sc.country_name = ac.country_name WHERE ISNULL(sc.country_name)