2

我想做这样的事情:

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*返回该行一次。我该如何解决这个问题?

4

3 回答 3

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

这是为什么首选ANSI连接语法(使用JOIN关键字)的一个很好的例子。

于 2012-04-24T10:18:03.673 回答
2
SELECT          Users.id,
                Countries.name
FROM            Users
LEFT OUTER JOIN Countries ON Users.country_id = Countries.id
于 2012-04-24T10:18:33.003 回答
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 );
于 2012-04-24T12:42:02.933 回答