gpt4 book ai didi

mysql - 为什么 mysql count(*) 比 count(id) 有更好的性能

转载 作者:可可西里 更新时间:2023-11-01 06:40:07 24 4
gpt4 key购买 nike

一开始我想比较count(*)和count(id),哪个性能更好?

mysql版本

5.6.21-1~dotdeb.1-log

表格信息

PRIMARY KEY (`id`),
KEY `is_availability` (`is_availability`,`is_del`)
ENGINE=InnoDB AUTO_INCREMENT=48993819 DEFAULT CHARSET=utf8
  1. 不用where条件比较

    select count(*) from op_log;
    +----------+
    | count(*) |
    +----------+
    | 48989975 |
    +----------+
    1 row in set (10.02 sec)

    select count(id) from op_log ;
    +-----------+
    | count(id) |
    +-----------+
    | 48989990 |
    +-----------+
    1 row in set (12.05 sec)

count(*) 优于 count(id)

  1. 与where条件比较

    select count(*) from op_log where is_availability=1;
    +----------+
    | count(*) |
    +----------+
    | 48990038 |
    +----------+
    1 row in set (15.86 sec)
    select count(id) from op_log where is_availability=1;
    +-----------+
    | count(id) |
    +-----------+
    | 48990096 |
    +-----------+
    1 row in set (17.13 sec)

    count(*) 仍然优于 count(id)

因此,如果我可以得出结论,count(*) 的性能优于 count(id),这是为什么?

高性能 MySQL,我得到了

if mysql knows some col cannot be NULL, it will optimize count(col) to count(*) internally

所以我怀疑花费更多的时间来做这个优化工作。

最佳答案

通常 COUNT(*) 的性能会稍好一些。 COUNT(id) 需要检查 id 是否不为 NULL 才能正常工作。这意味着它需要读取值(以及检查 NULLness 的小开销)。

id 是一个集群主键时,我希望大多数数据库的时间是相同的。然而,也许 MySQL 优化器不会费心避免 NULL 检查,即使对于声明为 NOT NULL 的列也是如此。

注意:在进行计时时,您必须非常小心,不要从冷缓存开始。在您的情况下,更快的查询似乎是第一次运行,因此缓存似乎不太可能解释性能差异。

关于mysql - 为什么 mysql count(*) 比 count(id) 有更好的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35653049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com