Ozz*_*zzy 16 mysql sql null left-join
我有这个问题
SELECT articles.*,
users.username AS `user`
FROM `articles`
LEFT JOIN `users` ON articles.user_id = users.id
ORDER BY articles.timestamp
Run Code Online (Sandbox Code Playgroud)
基本上它返回文章列表和文章关联的用户名.现在,如果users表中没有特定用户标识的条目,则usersvar为NULL.反正有没有,如果它的null返回类似"用户未找到"的东西?或者我必须使用PHP吗?
OMG*_*ies 35
使用:
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
Run Code Online (Sandbox Code Playgroud)
文档:
选择COALESCE而不是IF或IFNULL的原因是COALESCE是ANSI标准,而其他方法不能可靠地实现在其他数据库上.在我查看IF之前我会使用CASE,因为CASE是ANSI标准,因此更容易将查询移植到其他数据库.
您可以使用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
Run Code Online (Sandbox Code Playgroud)