如何获取最近30分钟内每分钟有时间的行

时间:2019-06-13 04:44:52

标签: mysql

juat like now, i need 30 rows for last 30 minutes

现在仅返回当前时间的一行,我希望每分钟最近30分钟有30行

1 个答案:

答案 0 :(得分:2)

对于每分钟的计数,解决方案不需要以下顺序:

SELECT MINUTE(timestamp) as m, COUNT(*)
FROM table
WHERE timestamp > DATE_SUB(NOW(), INTERVAL 30 MINUTE)
GROUP BY m

处理应用程序中没有条目的空白。

序列,如果有需要的话:

db fiddle

这是sequence of numbers的扩展:

SELECT
    DATE_SUB(NOW(), INTERVAL (TENS.SeqValue + ONES.SeqValue) MINUTE) as t
FROM
    (
    SELECT 0  SeqValue
    UNION ALL
    SELECT 1
    UNION ALL
    SELECT 2
    UNION ALL
    SELECT 3
    UNION ALL
    SELECT 4
    UNION ALL
    SELECT 5
    UNION ALL
    SELECT 6
    UNION ALL
    SELECT 7
    UNION ALL
    SELECT 8
    UNION ALL
    SELECT 9
    ) ONES
CROSS JOIN
    (
    SELECT 0 SeqValue
    UNION ALL
    SELECT 10
    UNION ALL
    SELECT 20
    ) TENS
ORDER BY t DESC

从10.0版开始的MariaDB具有一个sequence storage engine,可以简化解决方案:

SELECT
    DATE_SUB(NOW(), INTERVAL seq MINUTE) as t
FROM seq_0_to_30
ORDER BY t DESC