SQL 中获取 2 个表之间差异的最简单查询是什么?

What is the simplest query in SQL to get the differences between 2 tables?

有 2 个 table 列 Country,我试图在两个国家中获得相同国家的结果,一个国家在第一个 table 中,但是不是第二个,第二个是国家 table 但不是第一个。

Tb1.Country:

Botswana
Burkina Faso
Cameroon
Ethiopia
Ghana
Ghana
Ghana
Ghana
Ghana
Morocco
Nigeria
Nigeria
Nigeria
Sierra Leone
South Africa
South Africa
South Africa
South Africa
South Africa
South Africa
Tanzania
Zambia
India
India
India
India
Indonesia
Pakistan
Pakistan
Pakistan
Philippines
Thailand
Thailand

TB2.Country:

Angola
Botswana
Burkina Faso
Ethiopia
Ghana
Ghana
Ghana
Morocco
Nigeria
Nigeria
Nigeria
Rwanda
Sierra Leone
South Africa
South Africa
Tanzania
Zambia
India
India
Indonesia
Pakistan
Pakistan
Philippines
Sri Lanka
Thailand
Thailand

您可以在 Access 中使用 UNION 查询来执行此操作:

SELECT
    TB1.Country,
    "Country in Table 1, but not Table 2" as result
FROM
    tb1 
    LEFT JOIN tb2 ON
        tb1.country = tb2.country
WHERE tb2.country IS NULL

UNION ALL

SELECT
    TB2.Country,
    "Country in Table 2, but not Table 1"
FROM
    tb2 
    LEFT JOIN tb1 ON
        tb2.country = tb1.country
WHERE tb1.country IS NULL

UNION ALL

SELECT
    TB2.Country,
    "Country is in both tables"
FROM
    tb2 
    INNER JOIN tb1 ON
        tb2.country = tb1.country

这是三个用联合粘在一起的查询。第一个查找 table 1 中不在 Table 2 中的国家。第二个查找 table 2 中不在 table 1 中的国家,最后一个查询只有 returns 个国家/地区都属于这两个国家。

Simple Union 可以满足您的需求:

步骤 1 ) 这将为您提供 table 中的国家/地区,不会显示重复项。

SELECT Country FROM Tb1
UNION
SELECT Country FROM Tb2

第 2 步) 这将使您在第一个 table 而不是第二个国家:

Select  Country from Tb1
Where Country Not IN( 
Select Country from Tb2)

第 3 步)这会给你第二个 table 但不是第一个

的国家
Select  Country from Tb2
Where Country Not IN( 
Select Country from Tb1)

标准中有多个集合操作SQL,不仅有 UNION,还有 EXCEPT 和 INTERSECT。

获取两个 table 中共同的国家:

select country from t1
intersect
select country from t2

仅获取前table的国家:

select country from t1
except -- Oracle calls this MINUS
select country from t2

更改选择的顺序以获得 t2 中未在 t1 中找到的国家/地区。