gpt4 book ai didi

mysql - 在 SQL 查询中使用 else

转载 作者:行者123 更新时间:2023-11-29 02:15:19 24 4
gpt4 key购买 nike

我有以下查询,其中连接了几个表。其中一个表是 profile_img。此表包含已上传用户的个人资料图片,否则他们将获得 profile_images/default.jpg 并且该用户不在 profile_img 表中,所以我需要一个案例各种检查他们是否不在该表中,然后将他们的个人资料图片设置为默认图片。

这是我的查询。

    SELECT f.*, u.*, p.*
FROM friends f
LEFT JOIN
profile_img p
ON p.user_id = f.friend_one
JOIN
users u
ON u.id = f.friend_one
WHERE f.friend_two = ? AND f.status = ? AND
p.id = (select max(p2.id) from profile_img p2 where p2.user_id = p.user_id)

我尝试了 ,coalesce(p.img, 'profile_images/default.jpg') as img 来尝试获取结果,但没有帮助。

在另一个查询中:

(case when p.img <> '' then p.img
else 'profile_images/default.jpg'
end) as img

我只是不确定如何让它在这种情况下工作,而且它不适用于此。

最佳答案

@marekful 在使用 ifnull() 时是正确的,但还需要另一个修复。

在您的 where 子句中,您引用了 p.id =。由于当该用户没有 profile_img 行时 p 将为空,因此由于与空比较,整行将从结果中排除。

此查询考虑了空的 p.id 字段,并通过在 p.id 为空时允许 p.id 来包含它们。现在 p.image_url 将为 null 并且 ifnull() 方法将为这些行响应“default.png”。

SELECT f.*, u.*, p.*, IFNULL(p.image_url, 'default.png') AS profile_pic
FROM friends f
LEFT JOIN
profile_img p
ON p.user_id = f.friend_one
JOIN
users u
ON u.id = f.friend_one
WHERE
f.friend_two = ?
AND f.status = ?
AND ( p.id is null or p.id = (select max(p2.id) from profile_img p2 where p2.user_id = p.user_id) )

您也可以在没有 OR 子句的情况下通过将子查询添加到 ON 谓词来执行此操作。然后在连接之前解析子查询。

SELECT f.*, u.*, p.*, IFNULL(p.image_url, 'default.png') AS profile_pic
FROM friends f
JOIN
users u
ON u.id = f.friend_one
LEFT JOIN
profile_img p
ON p.user_id = f.friend_one and p.id = (select max(p2.id) from profile_img p2 where p2.user_id = p.user_id)
WHERE
f.friend_two = ?
AND f.status = ?

我不确定哪个性能更好。您必须亲自尝试一下。

关于mysql - 在 SQL 查询中使用 else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40811594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com