4

问个大佬 sql 问题

 2 years ago
source link: https://www.v2ex.com/t/789912
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

问个大佬 sql 问题

  somewheve · 1 天前 · 766 次点击
这个表只有 90w 行
我用 这个查询语句 SELECT count(0) FROM `con_sec_data_v2` 居然要耗时几分钟 。

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

为啥这么耗时啊 以及 sql 语句有其他的吗 ? ===> 查询当前表具体有多少行
7 条回复    2021-07-17 11:17:23 +08:00

zlowly

zlowly   1 天前

如果表上有主键的话,count (主键字段)可以只做索引扫描,应该会比全表扫描要快。

myd

myd   1 天前

如果是 Innodb 存储引擎,且没有创建辅助索引时,是要全表扫描才能获取到行数的。
即使有主键索引,也需要全表扫描。

你需要创建一个辅助索引,只需要扫描辅助索引即可获取到总行数,执行速度在 1 秒内。SQL 直接 count(*)也一样。

xx6412223

xx6412223   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

mikulch   1 天前

用你的表里面的,类型小,长度最少的列,创建一个二级索引。然后查询的时候使用 select count(column) from 'table' 来执行覆盖索引扫描,这样子的话就不用执行全表扫描了。

mikulch

mikulch   1 天前

@myd 不使用 count(列名)恐怕不行吧?

potatosmith

potatosmith   1 天前

Innodb 引擎不会存储表的总行数,求总数又不用索引的话只能全表扫描

onepunch

onepunch   15 小时 30 分钟前

闲着没事 count 全表干什么

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK