MySQL左连接为空结果

18

我有这个查询

SELECT articles.*, 
       users.username AS `user` 
 FROM `articles` 
LEFT JOIN `users` ON articles.user_id = users.id 
 ORDER BY articles.timestamp 

基本上它返回文章列表以及文章相关联的用户名。如果对于特定的用户ID在用户表中没有条目,则users变量为空。是否有办法使其返回类似于“未找到用户”的内容,如果它为空?还是我必须使用PHP来实现这个功能?

4个回答

38

使用:

   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 标准,而其他方法在其他数据库中的可靠性实现并不一定。如果要将查询移植到其他数据库中,我会先使用 CASE 而不是 IF,因为CASE也是 ANSI 标准。


6
你可以使用 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 

1

你可以使用IF(),在Oracle中你会使用decode。

因此

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,所以没有测试过这个查询。但是如果失败了,只需要进行一些小的修改就应该可以工作。请不要给我点踩;)

1

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

用户未找到的双引号?;) - OMG Ponies

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接