4
问个大佬 sql 问题
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.
这个表只有 90w 行
我用 这个查询语句 SELECT count(0) FROM `con_sec_data_v2` 居然要耗时几分钟 。
同时数据库一直在写入新的数据,包括其他表
为啥这么耗时啊 以及 sql 语句有其他的吗 ? ===> 查询当前表具体有多少行
我用 这个查询语句 SELECT count(0) FROM `con_sec_data_v2` 居然要耗时几分钟 。
同时数据库一直在写入新的数据,包括其他表
为啥这么耗时啊 以及 sql 语句有其他的吗 ? ===> 查询当前表具体有多少行
7 条回复 • 2021-07-17 11:17:23 +08:00
myd 1 天前
如果是 Innodb 存储引擎,且没有创建辅助索引时,是要全表扫描才能获取到行数的。
即使有主键索引,也需要全表扫描。
你需要创建一个辅助索引,只需要扫描辅助索引即可获取到总行数,执行速度在 1 秒内。SQL 直接 count(*)也一样。
即使有主键索引,也需要全表扫描。
你需要创建一个辅助索引,只需要扫描辅助索引即可获取到总行数,执行速度在 1 秒内。SQL 直接 count(*)也一样。
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 1 天前
用你的表里面的,类型小,长度最少的列,创建一个二级索引。然后查询的时候使用 select count(column) from 'table' 来执行覆盖索引扫描,这样子的话就不用执行全表扫描了。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK