MySQL内部联接查询以获取其他表中不存在的记录

sko*_*kos 12 mysql

我有表1,all_countries,如下 -

id   |  country
------------------
1    |  USA
2    |  China
3    |  India
4    |  France
5    |  UK
6    |  Australia
Run Code Online (Sandbox Code Playgroud)

我还有表2,supported_countries, -

id   |  country
------------------
1    |  USA
2    |  China
Run Code Online (Sandbox Code Playgroud)

现在我需要一个查询,它会给我包含所有不支持的国家/地区的结果

所以按照上面的例子,我应该得到

India
France
UK
Australia
Run Code Online (Sandbox Code Playgroud)

我使用以下查询 -

SELECT ac.country FROM all_countries ac INNER JOIN supported_countries sc ON sc.country_name!= ac.country_name

它工作正常,除非supported_countries表为空,它不显示任何记录.如何实现这个结果?

Joa*_*son 33

A LEFT JOIN会优雅地做到这一点;

SELECT a.* 
FROM all_countries a
LEFT JOIN supported_countries s
  ON a.country = s.country
WHERE s.id IS NULL;
Run Code Online (Sandbox Code Playgroud)

在这里演示.


IT *_*ppl 5

尝试如下操作:

SELECT * FROM all_countries 
  WHERE country NOT IN (SELECT country FROM supported_countries)
Run Code Online (Sandbox Code Playgroud)

  • 子查询通常比显式联接[性能较差](http://stackoverflow.com/questions/3856164/sql-joins-vs-sql-subqueries-performance)。它们更容易阅读,但扩展性较差。 (8认同)