大龙的博客

常用链接

统计

最新评论

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

 问题:有几个表,要把查询结果给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
 标题2  内容2
。。。
问题,怎么样可以做到:
id title content
 标题1  内容1   ---  属于表2
 标题2  内容2   ---  属于表1
。。。
答:
select * from (
 select id,title,content,'tbl1' as typename from 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
就可以了。
 

posted on 2011-12-30 15:22 大龙 阅读(375) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理