Mysql Left Join Null Result

前端 未结 4 900
慢半拍i
慢半拍i 2020-12-30 02:52

I have this query

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


        
相关标签:
4条回答
  • 2020-12-30 03:19

    You can use the IFNULL function:

    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 讨论(0)
  • 2020-12-30 03:26

    You can use IF() where in Oracle you would have used decode.

    So

    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 
    

    Should work. Note: I dont have mysql handy, so did not test the query. But should work with minor modifications if it fails. Do not downvote ;)

    0 讨论(0)
  • 2020-12-30 03:35
    
    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 讨论(0)
  • 2020-12-30 03:37

    Use:

       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 
    

    Documentation:

    • COALESCE

    The reason to choose COALESCE over IF or IFNULL is that COALESCE is ANSI standard, while the other methods are not reliably implemented over other databases. I would use CASE before I'd look at IF because again - CASE is ANSI standard, making it easier to port the query to other databases.

    0 讨论(0)
提交回复
热议问题