日期:2014-05-19  浏览次数:20540 次

多表查询(特别)
我现在一个库里面有多个表。

结构都是一样的。

相当于一个月生成的一张记录表

表名如

  xx_log_200702         指的是2007年2月份的记录
  xx_log_200703         指的是2007年3月份的记录
  xx_log_200704         指的是2007年4月份的记录


结构为
id
tel
msg
time
……几个字段


我现在如果想把这几个表的信息汇总,查询出来

怎么弄?




------解决方案--------------------
select * from xx_log_200702
union
select * from xx_log_200703
union
....
------解决方案--------------------
declare @strQuery nvarchar(4000)
set @strQuery= ' '
select @strQuery=N 'select * from '+name+N ' union all ' from sysobjects where name like N 'xx_log_% '
if len(@strQuery)> 0 set @strQuery=left(@strQuery,len(@strQuery)-10)
exec(@strQuery)
------解决方案--------------------
1.查询时利用Union All将多个表的内容联合到一起
select * from xx_log_200702
union ALL
select * from xx_log_200703

2.汇总时同样利用UNION ALL
Select 列名,SUM(列名) From (select * from xx_log_200702
union ALL
select * from xx_log_200703) A Group By 相应列名
------解决方案--------------------
建议LZ使用分区视图:
create view vLogWhole
as
select * from xx_log_200702
union all
select * from xx_log_200703
union all
select * from xx_log_200704
union all
....