需求
最近1小时 1分钟 60个点
最近3小时 5分钟 36个点
最近6小时 10分钟 36个点
最近12小时 20分钟 36个点
最近1天 1小时 24个点
最近3天 3小时 24个点
最近1周 6小时 28个点
如果你的递归查询支持递归CTE(如MySQL 8.0+),可以使用递归查询来生成平均分布的时间点。下面是一个示例,假设开始时间为 start_time,结束时间为 end_time,要取n个时间点:
sql
WITH RECURSIVE TimePoints AS (
SELECT TIMESTAMPADD(SECOND, 0, start_time) AS time_point, 1 AS point_number
UNION ALL
SELECT TIMESTAMPADD(SECOND, (UNIX_TIMESTAMP(end_time) - UNIX_TIMESTAMP(start_time)) / (n - 1) * point_number, start_time), point_number + 1
FROM TimePoints
WHERE point_number < n
)
SELECT time_point
FROM TimePoints;
解释:
WITH RECURSIVE TimePoints AS: 这部分定义了一个递归CTE,用于生成时间点序列。
SELECT TIMESTAMPADD(SECOND, 0, start_time) AS time_point, 1 AS point_number: 这是递归的起始部分,设置第一个时间点和计数器。
SELECT TIMESTAMPADD(SECOND, (UNIX_TIMESTAMP(end_time) - UNIX_TIMESTAMP(start_time)) / (n - 1) * point_number, start_time), point_number + 1: 这是递归部分,通过计算时间段的秒数差除以(n-1)来计算每个时间点的间隔。
WHERE point_number < n: 这个条件确保递归停止在生成n个时间点之后。
最后的 SELECT time_point FROM TimePoints: 返回生成的时间点序列。
例子:
sql
WITH RECURSIVE TimePoints AS (
SELECT TIMESTAMPADD(SECOND, 0, '2024-08-08 18:30:00') AS time_point, 1 AS point_number
UNION ALL
SELECT TIMESTAMPADD(SECOND, (UNIX_TIMESTAMP('2024-08-08 21:30:00') - UNIX_TIMESTAMP('2024-08-08 18:30:00')) / (6 - 1) * point_number, '2024-08-08 18:30:00'), point_number + 1
FROM TimePoints
WHERE point_number < 6
)
SELECT time_point,(SELECT name
FROM op_custom_config_tb
ORDER BY ABS(TIMESTAMPDIFF(SECOND, update_time, time_point))
LIMIT 1) aaa
FROM TimePoints;