V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
Geekerstar
V2EX  ›  MySQL

mysql 如何按时间维度每 5s 统计一次数据呢?

  •  
  •   Geekerstar · 2021-09-22 14:03:03 +08:00 · 2277 次点击
    这是一个创建于 918 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有个表有创建时间字段,按照这个字段,每隔 5 秒统计一次这期间的数据增量,如果没有新增,则为 0,这种 SQL 怎么写呢?

    13 条回复    2021-09-23 09:12:59 +08:00
    myd
        1
    myd  
       2021-09-22 14:08:03 +08:00
    select count(*) from xxx group by floor(时间戳 /5)
    Geekerstar
        2
    Geekerstar  
    OP
       2021-09-22 14:17:38 +08:00
    @myd

    2021-09-22 13:45:29 1
    2021-09-22 13:45:30 2
    2021-09-22 13:46:00 4
    2021-09-22 13:46:07 1
    2021-09-22 13:46:30 2

    不是每秒钟都有数据,有没有办法能整齐的每五秒分割一次来进行统计呢?
    myd
        3
    myd  
       2021-09-22 14:28:43 +08:00
    @Geekerstar 在程序中补齐,不一定要在数据库中实现。
    deltadawn
        4
    deltadawn  
       2021-09-22 14:35:54 +08:00
    INTERVAL()
    Pipecraft
        5
    Pipecraft  
       2021-09-22 15:46:50 +08:00   ❤️ 2
    试了一下,使用 `DATE_ADD(created_at, INTERVAL - SECOND(created_at) % 5 SECOND)` 可以按照每分钟的 0,5,10.. 秒为单位统计。没有数据的时间段需要在程序补齐。

    由于无法贴出代码,我把完整的 SQL 贴在了这里 pzwd.net/d/31/2
    wellsc
        6
    wellsc  
       2021-09-22 15:53:36 +08:00
    用 Prometheus 吧
    adgad2
        7
    adgad2  
       2021-09-22 16:01:33 +08:00
    遇到个类似需求,最后建表写个定时任务完事
    haochen2
        8
    haochen2  
       2021-09-22 16:10:58 +08:00
    这种统计的还是多余建个表来存储吧
    Geekerstar
        9
    Geekerstar  
    OP
       2021-09-22 16:14:11 +08:00
    @Pipecraft 感谢大佬
    Geekerstar
        10
    Geekerstar  
    OP
       2021-09-22 16:14:31 +08:00
    @myd 嗯嗯,在程序中处理了
    Geekerstar
        11
    Geekerstar  
    OP
       2021-09-22 16:15:37 +08:00   ❤️ 1
    @Pipecraft 大佬的网站很棒,收藏了
    beginor
        12
    beginor  
       2021-09-22 16:40:18 +08:00 via Android
    不知道 mysql 有没有类似 PostgreSQL 生成序列的概念,有的话就很容易统计了
    Saxton
        13
    Saxton  
       2021-09-23 09:12:59 +08:00
    我做过这个需求,先 count 查出来,然后用程序补充时间就可以了 mysql 只负责查 不负责逻辑的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5494 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 08:55 · PVG 16:55 · LAX 01:55 · JFK 04:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.