sql - 如何将 2 个表中的 2 列连接到一个列中?
问题描述
我有 3 张桌子:
表格1:
app_id| reference
-----------------
123 | table2
124 | table3
表2:
app_id| info
-----------------
123 | test app1
表3:
app_id| app_info
-----------------
124 | test app2
问题:我如何使 SQL 返回下表?
app_id| information
-----------------
123 | test app1
124 | test app2
我可以写一个这样的查询:
SELECT t1.app_id, t2.info, t3.app_info
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON t1.app_id = t2.app_id
LEFT JOIN Table3 AS t3 ON t1.app_id = t3.app_id
但我不希望 t2.info、t3.app_info 作为 2 个单独的字段,我希望它返回单个“信息”列,其中包含两个表中的连接数据。
解决方案
将添加COALESCE
功能:
SELECT t1.app_id, coalesce(t2.info, t3.app_info) information
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON t1.app_id = t2.app_id
LEFT JOIN Table3 AS t3 ON t1.app_id = t3.app_id
;
• SQL Fiddle (MS SQL Server 2017) • COALESCE
的文档
推荐阅读
- ios - CADisplayLink 回调是否总是在主线程上运行?
- laravel - SQLSTATE [42000]:语法错误或访问冲突:Laravel 中的 1064 和 MariaDB 迁移中的错误
- arm - U-Boot: "go" vs "bootz" with zImage
- python-3.x - 为什么我们在这个基于 ajax 的音乐网站中使用 Selenium 得到空白文本?
- docker - docker-compose 中的 ASP 配置环境变量
- ios - 操作扩展,在即时标记中获取图像返回一个空白屏幕
- javascript - 使用动态选项卡和 codeigniter 加载不同的页面
- javascript - 在 Angular 中扩展与注入
- typescript - 将地理位置转换为墨卡托投影图像上的像素
- javascript - 单击静音按钮时页面刷新不适用于音频