储存过程:
drop procedure if exists unionsp;delimiter //create procedure unionsp(stime varchar(32), etime varchar(32),tchema varchar(32))begindeclare sqlvar varchar(1024000);declare rest int;declare tablename varchar(1024);set rest = 100;set sqlvar='';while rest > 0 do set stime = (select date_format((select adddate(stime,1)),'%y%m%d')); set tablename=concat('tbl_req_',stime); select count(1) from information_schema.tables where table_name = tablename and table_schema=tchema into @cnt; if @cnt != 0 then if rest=1 then set sqlvar=concat(sqlvar,' select distinct channel_id,app_id from tbl_req_',stime); else set sqlvar=concat(sqlvar,' select distinct channel_id,app_id from tbl_req_',stime,' union'); end if;end if;set rest = datediff(etime,stime);end while;set @v_s=sqlvar;prepare stmt from @v_s;execute stmt;deallocate prepare stmt;end;// delimiter;call unionsp('20140730','20140930','biz_date')
union:联合的意思,即把两次或多次查询结果合并起来。
要求:两次查询的列数必须一致
推荐:列的类型可以不一样,但推荐查询的每一列,想对应的类型以一样
可以来自多张表的数据:多次sql语句取出的列名可以不一致,此时以第一个sql语句的列名为准。
如果不同的语句中取出的行,有完全相同(这里表示的是每个列的值都相同),那么union会将相同的行合并,最终只保留一行。也可以这样理解,union会去掉重复的行。
如果不想去掉重复的行,可以使用union all
