Mysql 对可能包含NULL的列进行联接
我想这样做:Mysql 对可能包含NULL的列进行联接,mysql,sql,Mysql,Sql,我想这样做: SELECT Users.id, Countries.name FROM Users, Countries WHERE Users.country_id = Countries.id 问题是,Users.country\u id有时可能为NULL,如果为空,则不会返回整行。我希望它返回该行,但该列中包含“null”或“”。我试过这个: SELECT Users.id, Countries.name FROM Users
SELECT
Users.id,
Countries.name
FROM
Users, Countries
WHERE
Users.country_id = Countries.id
问题是,Users.country\u 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
*,它只返回一次行。我如何解决这个问题
SELECT users.id, countries.name
FROM users
LEFT JOIN
countries
ON countries.id = users.country_id
这是一个很好的例子,说明了为什么首选
ANSI
join语法(使用join
关键字)。您可以使用外部联接。谢谢。这很有效。出于好奇,我还尝试了“左外连接”,它也很有效。@alnafie:OUTER
是纯语法糖。这意味着左外连接
与左连接
(语法糖,哈哈)左外连接
是不精确的语法糖;)<代码>联合将执行不必要的工作以消除重复项。应该使用联合体。但是,整个查询是不必要的,存在外部联接,mysql支持它。@FlorinGhita:“整个查询是不必要的[sic]”——您似乎在暗示使用外部联接是必要的:想证明一下吗OUTER JOIN
无论如何都是一种并集,一种专门设计用来生成空值的并集,我更喜欢避免空值。
SELECT Users.id,
Countries.name
FROM Users
LEFT OUTER JOIN Countries ON Users.country_id = Countries.id
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 );