views:

138

answers:

4

I have this query

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

Basically it returns the list of articles and the username that the article is associated to. Now if there is no entry in the users table for a particular user id, the users var is NULL. Is there anyway to make it that if its null it returns something like "User Not Found"? or would i have to do this using php?

+5  A: 

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:

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.

OMG Ponies
Thanks so much :)
Ozzy
gota wait 8 minutes to accept... :P
Ozzy
A: 

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

So

SELECT articles.*, IF(users.username=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 ;)

ring bearer
+2  A: 

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 
Sean Reilly
A: 

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
Christian Jonassen
Double quotes on User Not Found? ;)
OMG Ponies
Not recommended. :)
Christian Jonassen