储存过程其实是多个sql的集合,常常用于一些数据整合或者定时任务的执行。以下是我第一个储存过程留念。
BEGIN declare now_time datetime;#当前系统时间 declare start_time datetime;#开始时间 declare end_time datetime;#结束时间 #搬运是时间为空,则取7天前的数据 if aim_time is not null then set now_time = aim_time; set start_time = DATE_SUB(timestamp(date(now())), INTERVAL 7 DAY); set end_time = DATE_SUB(timestamp(date(now())), INTERVAL 6 DAY); else set now_time = now(); set start_time = timestamp(adddate(date(now_time), -1)); set end_time = timestamp(date(now_time)); end if; #临时表不能重复 DROP TEMPORARY TABLE IF EXISTS `t_temp_user_device_info`; #最终成型的表结构,此为临时表 CREATE TEMPORARY TABLE `t_temp_user_device_info` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `device_info_id` varchar(20) COLLATE utf8_general_ci NOT NULL COMMENT '设备主键', `did` varchar(20) COLLATE utf8_general_ci NOT NULL COMMENT '设备号', `create_time` datetime DEFAULT NULL COMMENT '激活时间', PRIMARY KEY (`id`) ); #将必要信息存入临时表 INSERT INTO t_temp_user_device_info (device_info_id, did, create_time) SELECT t2.id, t1.did, t1.create_time FROM ( SELECT did, create_time FROM u_user_device_info where type = 1 AND create_time BETWEEN start_time AND end_time ) t1 INNER JOIN t_device_info t2 on t2.did = t1.did; #把数据插入正式表 INSERT INTO t_count_user_device_info (did, reg_code, phone, path, sex, height, birthday, insterests, address, school) SELECT t4.did, t1.reg_code, t2.phone, t3.path, t3.sex, t3.height, t3.birthday, t3.interests, t3.address, t3.school FROM t_temp_user_device_info t4 LEFT JOIN t_device_reg_code_info t1 ON t4.did = t1.did LEFT JOIN t_device_phone t2 ON t4.did = t2.did LEFT JOIN t_bady_info t3 ON t4.device_info_id = t3.device_info_id; #SELECT * FROM t_count_user_device_info; #判断并删除临时表 TRUNCATE TABLE t_temp_user_device_info; DROP TEMPORARY TABLE IF EXISTS t_temp_user_device_info; END
sql中sum()函数和if的搭配用法。
SELECT COUNT(*) total, sum(if(phone is null, 1, 0)) pnum, sum(if(birthday is null, 1, 0)) bnum FROM ( SELECT t4.did, t1.reg_code, t2.phone, t3.path, t3.sex, t3.height, t3.birthday, t3.interests, t3.address, t3.school, t4.create_time FROM t_temp_user_device_info t4 LEFT JOIN t_device_reg_code_info t1 ON t4.did = t1.did LEFT JOIN t_device_phone t2 ON t4.did = t2.did LEFT JOIN t_bady_info t3 ON t4.device_info_id = t3.device_info_id ) tt;