說明:主要作用於一些統計數據,來根據時間順序進行顯示;
假如資料庫數據有隔天數據,偏偏統計又需要每天的都顯示,即使是0,那就要產生一個時間表,來使用;
查詢資料庫資料:
SELECT DATE_FORMAT( create_time, '%Y-%m-%d' ) AS date, COUNT(1) AS numb FROM 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 numb FROM 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' )) t right 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如何產生連續日期及變數賦值的詳細內容。更多資訊請關注PHP中文網其他相關文章!