问题:有几个表,要把查询结果给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
就可以了。
本文介绍如何在使用SQL的UNION ALL操作时为每个表的结果集添加一个标识字段,以便区分不同的表来源。通过在每个SELECT语句中增加一个额外的字段来标记表名,实现了合并多个表数据的同时保留原始表的信息。
907

被折叠的 条评论
为什么被折叠?



