在可能包含NULL的列上加入

时间:2012-04-24 10:15:47

标签: mysql sql

我想做这样的事情:

SELECT
    Users.id,
    Countries.name 
FROM
    Users, Countries
WHERE 
    Users.country_id = Countries.id

问题是Users.country_id有时可能是NULL,如果是,则不返回整行。我希望它返回行但在该列中使用'null'或''。我试过这个:

SELECT
    Users.id,
    Countries.name 
FROM
    Users, Countries
WHERE 
    (Users.country_id = Countries.id OR Users.country_id IS NULL)

然而,对于存在的每个 * Countries.id * 会返回一行 > 即可。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:6)

SELECT  users.id, countries.name
FROM    users
LEFT JOIN
        countries
ON      countries.id = users.country_id

这是一个很好的示例,说明为什么ANSI加入语法(使用JOIN关键字)是首选。

答案 1 :(得分:2)

SELECT          Users.id,
                Countries.name
FROM            Users
LEFT OUTER JOIN Countries ON Users.country_id = Countries.id

答案 2 :(得分:0)

SELECT
    Users.id,
    Countries.name 
FROM
    Users, Countries
WHERE 
    Users.country_id = Countries.id
UNION
SELECT
    id,
    '{{no country}}' AS name 
FROM
    Users
WHERE 
   NOT EXISTS ( SELECT * 
                  FROM Countries
                 WHERE Users.country_id = Countries.id );