读书人

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

发布时间: 2012-03-30 17:32:09 作者: rapoo

Select Union all 怎样对记录进行区分
有四个相同的表tb1,tb2,tb3,tb4,就是表名不一样,有相同的字段比如说ID,Title,Content,怎样一句Select 同时返回四个表中的符合条件的

承接昨天的小问题.

下面这样用联合很好,但是怎样附加返回每一条记录所在表对应的表名?以示区分??

select * from
(
Select ID,Title,Content from tb1
union all
Select ID,Title,Content from tb2
union all
Select ID,Title,Content from tb3
union all
Select ID,Title,Content from tb4
) t
where title like "%myname% "



比如有两条记录:
id=2,Tittle= "a ",Content= "aaa " -------tb1中
id=2,Tittle= "a ",Content= "aaa " -------tb2中

要想区分必须得返回一个值吧?

[解决办法]
select * from
(
Select ID,Title,Content, 'tb1 ' as tablename from tb1
union all
Select ID,Title,Content,tb2 ' from tb2
union all
Select ID,Title,Content, 'tb3 ' from tb3
union all
Select ID,Title,Content, 'tb4 ' from tb4
) t
where title like "%myname% "

读书人网 >SQL Server

热点推荐