2010-05-24 99 views
15

我有這個疑問MySQL的左連接空結果

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

基本上它返回的文章列表,並將本條關聯到的用戶名。現在,如果用戶表中沒有特定用戶標識的條目,則users var爲NULL。無論如何要做到這一點,如果它的null返回類似「未找到用戶」?或者我將不得不這樣做使用PHP?

回答

33

用途:

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標準,可以更輕鬆地將查詢移植到其他數據庫。

+0

GOTA等待8分鐘接受...:P上的用戶 – Ozzy 2010-05-24 00:20:04

1

您可以使用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方便,所以沒有測試查詢。但如果失敗,應該稍作修改。不要downvote;)

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 
0

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 
+0

雙引號沒有發現? ;) – 2010-05-24 00:25:24

+0

不推薦。 :) – 2010-05-24 00:34:23