SARUAV
SARUAV

Reputation: 188

Return default value if no results found in SQL query

I currently am using this query to select "profile_picture from the column relation and table media, although I noticed my return default.png inside my html image tag doesn't work for results. Is there any way I could return: IF error

"SELECT * FROM media WHERE post_id = '5552773e65a2b' AND relation = 'profile_picture"

My current query

"SELECT * FROM media WHERE userID = $friend->user_id AND relation = 'profile_picture' ORDER BY id DESC LIMIT 1"

Upvotes: 0

Views: 211

Answers (1)

sgeddes
sgeddes

Reputation: 62851

While this would probably be easier to handle with your scripting language, you could do a union all to get the default value since you're ordering by the id field:

SELECT id, picture 
FROM media 
WHERE userID = $friend->user_id 
    AND relation = 'profile_picture' 
UNION ALL 
SELECT -1 id, 'default.png' picture
ORDER BY id DESC LIMIT 1

Upvotes: 1

Related Questions