V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
somewheve
V2EX  ›  程序员

问个大佬 sql 问题

  •  
  •   somewheve · Jul 16, 2021 · 2814 views
    This topic created in 1745 days ago, the information mentioned may be changed or developed.
    这个表只有 90w 行
    我用 这个查询语句 SELECT count(0) FROM `con_sec_data_v2` 居然要耗时几分钟 。

    同时数据库一直在写入新的数据,包括其他表

    为啥这么耗时啊 以及 sql 语句有其他的吗 ? ===> 查询当前表具体有多少行
    9 replies    2021-07-19 11:03:25 +08:00
    zlowly
        1
    zlowly  
       Jul 16, 2021
    如果表上有主键的话,count (主键字段)可以只做索引扫描,应该会比全表扫描要快。
    myd
        2
    myd  
       Jul 16, 2021
    如果是 Innodb 存储引擎,且没有创建辅助索引时,是要全表扫描才能获取到行数的。
    即使有主键索引,也需要全表扫描。

    你需要创建一个辅助索引,只需要扫描辅助索引即可获取到总行数,执行速度在 1 秒内。SQL 直接 count(*)也一样。
    xx6412223
        3
    xx6412223  
       Jul 16, 2021   ❤️ 1
    Prior to MySQL 5.7.18, InnoDB processes SELECT COUNT(*) statements by scanning the clustered index. As of MySQL 5.7.18, InnoDB processes SELECT COUNT(*) statements by traversing the smallest available secondary index unless an index or optimizer hint directs the optimizer to use a different index. If a secondary index is not present, the clustered index is scanned.

    创建一个辅助索引,建议用最小字段创建
    mikulch
        4
    mikulch  
       Jul 16, 2021
    用你的表里面的,类型小,长度最少的列,创建一个二级索引。然后查询的时候使用 select count(column) from 'table' 来执行覆盖索引扫描,这样子的话就不用执行全表扫描了。
    mikulch
        5
    mikulch  
       Jul 16, 2021
    @myd 不使用 count(列名)恐怕不行吧?
    potatosmith
        6
    potatosmith  
       Jul 16, 2021
    Innodb 引擎不会存储表的总行数,求总数又不用索引的话只能全表扫描
    onepunch
        7
    onepunch  
       Jul 17, 2021
    闲着没事 count 全表干什么
    zhanggang807
        9
    zhanggang807  
       Jul 19, 2021
    @JasonLaw bingo
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5986 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 639ms · UTC 03:25 · PVG 11:25 · LAX 20:25 · JFK 23:25
    ♥ Do have faith in what you're doing.