问题:有几个表,要把查询结果给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
就可以了。