从两个不同的表中选择

时间:2014-01-18 08:33:56

标签: mysql sql left-join

我需要你的帮助。假设我有以下假表 enter image description here

和另一张假表 enter image description here

我想要的是提出下表

enter image description here

select b.Country, b.AnotherCode, a.Code from Country1 a, Country2 b where a.Country=b.Country

(主键是国家)但它不显示最后两行。如何这样做,它将检索最后一个表中显示的所有行。谢谢inadvance

2 个答案:

答案 0 :(得分:2)

select b.Country, b.AnotherCode, a.Code from Country1 a left join Country2 b on a.Country=b.Country

使用左连接

答案 1 :(得分:0)

您将返回两个集合的交集 - 如果您想要设置所有行,您可以使用完整的连接:

SELECT      COALESCE(a.Country, b.Country) AS Country, 
            COALESCE(b.AnotherCode, 0) AS AnotherCode, 
            COALESCE(a.Code, 0) AS Code
FROM        Country1 a
FULL JOIN   Country2 b 
    ON      a.Country = b.Country

当然,如果您只想要来自Country1的记录以及来自Country2的任何相应值,那么LEFT JOIN就足够了。同样,如果在连接失败时需要不同的默认值,请更改COALESCE

中的值