如何在使用UNION时返回源表名?

Ars*_*hra 2 sql

如果我使用UNION从5个表中选择列,然后从结果中选择一个特定值,我该如何确定该值来自哪个表?

And*_*y M 9

在您要提取的其他列的列中提供表名称:

SELECT
  'table1' AS tablename,
  other columns
FROM table1

UNION ALL

SELECT
  'table2' AS tablename,
  other columns
FROM table2

UNION ALL

…
Run Code Online (Sandbox Code Playgroud)


vla*_*lad 5

在结果列表中添加一列,说明数据来自哪个表.例如:

select 'table1' tableName,
       columnA,
       columnB
from table1
union
select 'table2' tableName,
       columnC,
       columnD
Run Code Online (Sandbox Code Playgroud)