首页 > 解决方案 > 简单的 SQL 问题,如果没有 SQL 中的 IF、ELSE 语句,我将无法解决

问题描述

这是交易

我有两张桌子。第一个叫“男孩”

**ID    bestFriend  notBestFriend**
boy1    f123    f123 /
boy2    f456    f789 /
boy3    (null)  f852 /

第二个叫“朋友”

**friendID  fullName**
f123    Tim /
f456    Ron /
f789    Bud /
f852    Jack

我需要编写一个 SQL 查询,为每个男孩返回最好朋友的全名(如果存在),否则返回 notBestFriend 全名

标签: sqlleft-joinwhere-clause

解决方案


你可以left join两次:

select b.*, coalesce(f1.fullname, f2.fullname) friend_fullname
from boys b
left join friends f1 on f1.friendid = b.bestfriend
left join friends f2 on f2.friendid = b.notbestfriend

推荐阅读