1、生产连续日期说明:主要作用于一些统计数据,来根据时间顺序进行显示;
假如数据库数据有隔天数据,偏偏统计又需要每天的都显示,即便是0,那就要生成一个时间表,来使用;
查询数据库数据:
select date_format( create_time, '%y-%m-%d' ) as date, count(1) as numbfrom qc_task where create_time>= date_sub(curdate(),interval 1 month) and department_id in ( select id from `vigilante_jinan`.`qc_department` where `area_code` = (@dep_bh) and `status` = '1' and dept_level >= (@dep_dj)) group by date_format( create_time, '%y-%m-%d' )
隔天时出数据:
这样是不是就不好看了,如果非要说加个order by 1 desc 排一下,也可以…
但是就算排出来,时间也是不连贯的;
生成最近7天的日期:
// 方法笨,但还是有效的select date_format(subdate(now(), interval (timelist.sj*1460) minute),'%y-%m-%d') as 'datetime' from (select @num:=@num+1 as sj from (select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7) t, -- (select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7) t1, -- 假如嫌弃生成的少,打来这个就行 (select @num:=0) y) as timelist
生成的时间:
生成后使用:
-- 生成后左右链接即可,但主表要为时间表select f.datetime, t.numb from (select date_format( create_time, '%y-%m-%d' ) as date, count(1) as numbfrom qc_task where create_time>= date_sub(curdate(),interval 1 month) and department_id in ( select id from `vigilante_jinan`.`qc_department` where `area_code` = (@dep_bh) and `status` = '1' and dept_level >= (@dep_dj)) group by date_format( create_time, '%y-%m-%d' )) tright join (select date_format(subdate(now(), interval (timelist.sj*1460) minute),'%y-%m-%d') as 'datetime' from (select @num:=@num+1 as sj from (select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7) t, (select @num:=0) y) as timelist) f on t.date = f.datetime ;
使用后效果:
我这里是数据库没有数据…所以看不到有数量显示
2、变量赋值看到第一个里面 @符号很多是吗,那些都是变量,如果把查询语句放进去,整个查询语句就显得太臃肿了,会很长…所以有些东西可以拆分出去;
比如在查询数据库语句中的:
来看下他们的真面目:
# 查询部门区域编号select @dep_bh:=(select area_code from qc_department where dept_name = "历下区");# 查询部门等级select @dep_dj:=(select dept_level from qc_department where dept_name = "历下区");
以上就是mysql如何生成连续日期及变量赋值的详细内容。