MySQL存储过程 获取最近一段时间 - yiyixiaozhi/readingNotes GitHub Wiki
title: MySQL存储过程,列出获取最近一段时间 date: 2020-3-10 description: MySQL存储过程,列出获取最近一段时间 categories: - 工具 tags: - MySQL - 存储过程
思路:以当前时间为准,循环计算时间,计算的结果放到临时表中。 获取最近的10分钟,将每秒都列出来
CREATE DEFINER=`yyxz`@`%` PROCEDURE `last_ten_min`()
BEGIN
declare now_time timestamp;
declare sec int;
drop table if exists tmp_table_01;
CREATE TEMPORARY TABLE tmp_table_01(
`sec_time` timestamp
);
set now_time=now();
set sec=0;
while sec < 1000 do
set sec = sec + 1;
if sec mod 100 >= 60 then
set sec = (sec div 100 + 1) * 100;
end if;
INSERT INTO tmp_table_01 (`sec_time`) VALUES (SUBTIME(now_time, sec));
end while;
END
查看效果:
CALL last_ten_min();
select * from tmp_table_01;
SELECT
DATE_FORMAT(entry_time, '%Y-%m-%d %k:%i:%s') AS X,
COUNT(id) AS Y
FROM
t_student_entry_record
WHERE entry_time BETWEEN SUBTIME(NOW(), 1000) AND NOW()
GROUP BY entry_time
SELECT
DATE_FORMAT(tt01.sec_time, '%Y-%m-%d %k:%i:%s') AS X,
COUNT(tser.id) AS Y
FROM
(SELECT id, entry_time FROM t_student_entry_record where entry_time between subtime(now(), 1000) and now()) AS tser
RIGHT JOIN tmp_table_01 AS tt01 ON tser.`entry_time` = tt01.sec_time
GROUP BY
tt01.sec_time
ORDER BY tt01.sec_time