This topic created in 1763 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
 |
|
1
zlowly Jul 16, 2021
如果表上有主键的话,count (主键字段)可以只做索引扫描,应该会比全表扫描要快。
|
 |
|
2
myd Jul 16, 2021
如果是 Innodb 存储引擎,且没有创建辅助索引时,是要全表扫描才能获取到行数的。 即使有主键索引,也需要全表扫描。
你需要创建一个辅助索引,只需要扫描辅助索引即可获取到总行数,执行速度在 1 秒内。SQL 直接 count(*)也一样。
|
 |
|
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.
创建一个辅助索引,建议用最小字段创建
|
 |
|
4
mikulch Jul 16, 2021
用你的表里面的,类型小,长度最少的列,创建一个二级索引。然后查询的时候使用 select count(column) from 'table' 来执行覆盖索引扫描,这样子的话就不用执行全表扫描了。
|
 |
|
6
potatosmith Jul 16, 2021
Innodb 引擎不会存储表的总行数,求总数又不用索引的话只能全表扫描
|
 |
|
7
onepunch Jul 17, 2021
闲着没事 count 全表干什么
|