Select Union all 怎样对记录进行区分

本文介绍如何在使用SQL的UNION ALL操作时为每个表的结果集添加一个标识字段,以便区分不同的表来源。通过在每个SELECT语句中增加一个额外的字段来标记表名,实现了合并多个表数据的同时保留原始表的信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:有几个表,要把查询结果给union起来,但是这些表除表名不同外,没有一个字段区分它们。
比如
表1,表2,表3
都有字段id, title ,content
然后
select * from (
select id,title,content from tbl_1 where xxx
union ALL
select id,title,content from tbl_2 where xxx
union ALL
select id,title,content from tbl_3 where xxx
) T
结果是
id title content
1标题1 内容1
2 标题2 内容2
。。。
问题,怎么样可以做到:
id title content
1标题1 内容1 --- 属于表2
2 标题2 内容2 --- 属于表1
。。。
答:
select * from (
select id,title,content, 'tbl1' as typenamefrom tbl_1 where xxx
union ALL
select id,title,content, 'tbl2' as typename from tbl_2 where xxx
union ALL
select id,title,content , 'tbl3' as typename from tbl_3 where xxx
) T
就可以了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值