2012-03-31 47 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)