Home > Database > Mysql Tutorial > body text

mysql多日志表结果集合拼接存储过程_MySQL

WBOY
Release: 2016-06-01 13:02:41
Original
1159 people have browsed it

通常单天的日志 只记录当天的日志信息,如果需要查看一月内的日志信息需要对每天的日志表结果集合进行拼接,通常用到 union 。

储存过程:

drop PROCEDURE if  EXISTS unionSp;
DELIMITER //
create procedure unionSp(sTime varchar(32), eTime varchar(32),tchema varchar(32))

begin

declare 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') 
Copy after login

union:联合的意思,即把两次或多次查询结果合并起来。
要求:两次查询的列数必须一致
推荐:列的类型可以不一样,但推荐查询的每一列,想对应的类型以一样
可以来自多张表的数据:多次sql语句取出的列名可以不一致,此时以第一个sql语句的列名为准。
如果不同的语句中取出的行,有完全相同(这里表示的是每个列的值都相同),那么union会将相同的行合并,最终只保留一行。也可以这样理解,union会去掉重复的行。
如果不想去掉重复的行,可以使用union all

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!