【问题标题】:Mysql Left Join Null ResultMysql左连接空结果
【发布时间】:2011-02-23 01:23:10
【问题描述】:
我有这个问题
SELECT articles.*,
users.username AS `user`
FROM `articles`
LEFT JOIN `users` ON articles.user_id = users.id
ORDER BY articles.timestamp
基本上它返回文章列表和文章关联的用户名。现在,如果用户表中没有特定用户 ID 的条目,则 users var 为 NULL。无论如何,如果它为空,它会返回类似“用户未找到”的东西吗?还是我必须使用 php 来做到这一点?
【问题讨论】:
标签:
sql
mysql
null
left-join
【解决方案1】:
用途:
SELECT a.*,
COALESCE(u.username, 'User Not Found') AS `user`
FROM ARTICLES a
LEFT JOIN USERS u ON u.id = a.user_id
ORDER BY articles.timestamp
文档:
选择 COALESCE 而不是 IF 或 IFNULL 的原因是 COALESCE 是 ANSI 标准,而其他方法无法在其他数据库上可靠地实现。在查看 IF 之前,我会使用 CASE,因为 CASE 是 ANSI 标准,可以更轻松地将查询移植到其他数据库。
【解决方案2】:
您可以使用 IF() 在 Oracle 中您会使用解码的地方。
所以
SELECT articles.*, IF(users.username IS NULL, 'No user found', users.username) AS `user`
FROM `articles` LEFT JOIN `users` ON articles.user_id = users.id
ORDER BY articles.timestamp
应该可以。
注意:我手边没有mysql,所以没有测试查询。但如果失败,应该进行小的修改。不要投反对票;)
【解决方案3】:
你可以使用IFNULL函数:
SELECT articles.*, IFNULL(users.username, 'User Not Found') AS `user`
FROM `articles` LEFT JOIN `users` ON articles.user_id = users.id
ORDER BY articles.timestamp
【解决方案4】:
SELECT articles.*,
IFNULL(users.username,'User Not Found') AS `user`
FROM `articles`
LEFT JOIN `users` ON articles.user_id = users.id
ORDER BY articles.timestamp