首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

多表查询(特别),该如何处理

2012-01-21 
多表查询(特别)我现在一个库里面有多个表。结构都是一样的。相当于一个月生成的一张记录表表名如xx_log_2007

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

结构都是一样的。

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

表名如

  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
....

热点排行
Bad Request.