首页 > 解决方案 > 如何将 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 个单独的字段,我希望它返回单个“信息”列,其中包含两个表中的连接数据。

标签: sqlsql-servertsqljoin

解决方案


将添加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
的文档


推荐阅读