sql - 简单的 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 全名
解决方案
你可以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
推荐阅读
- mongodb - 如何使用 $In 在嵌套数组中使用项目来获取数据
- android - 列表视图中突出显示的项目仍然是 android
- codenameone - CN.setScreenSaverEnabled(false); 和媒体播放器
- selectedindexchanged - 使用角度 9 中的 selectedIndex 以编程方式更新选择选项时未触发更改事件
- java - 使用 DateTimeFormatter 的索引解析问题
- python - 一种在python列表中查找出现次数最多的项目及其出现次数的pythonic方法?
- terminal - 如何从 Windows Explorer URL 打开 Anaconda Prompt?
- c - int variable_name(0); 是什么?意思是?
- python - 如何优化数据框,以便每次使用日志都不会打印相同的输出?
- c++ - 错误:使用 != 比较迭代器时,二进制表达式的操作数无效