简单的 SQL 问题,如果没有 SQL 中的 IF、ELSE 语句我无法解决

Easy SQL problem i can't solve without IF, ELSE statement in SQL

这是交易

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

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

第二个叫“朋友”

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

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

你可以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

您可以在 ON 子句中使用 CASE WHEN 语句,根据列“bestfriend”是否为 NULL 指定要用于 JOIN 的列与否:

SELECT ID, fullName as friendName
  FROM t1
  JOIN t2
    ON (CASE WHEN (t1.bestFriend IS NOT NULL 
                   AND t1.bestFriend = t2.friendID) THEN 1
             WHEN (t1.bestFriend IS NULL 
                   AND t1.notBestFriend = t2.friendID) THEN 1
        END) = 1
;

这将为问题中的示例数据生成以下结果:

ID     friendName 
=================
boy1   Tim
boy2   Ron
boy3   Jack