如果在SQL查询中找不到结果,则返回默认值

时间:2021-12-31 20:10:22

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

我目前正在使用此查询从列关系和表媒体中选择“profile_picture,虽然我注意到我的html图像标记内的return default.png对结果不起作用。有什么方法可以返回:IF错误

"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"

1 个解决方案

#1


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:

虽然使用脚本语言可能更容易处理,但您可以使用union all来获取默认值,因为您按id字段进行排序:

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

#1


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:

虽然使用脚本语言可能更容易处理,但您可以使用union all来获取默认值,因为您按id字段进行排序:

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