关于 withCount

withCount 能指定 count (id) 这个字段吗,count (*) 太影响性能了

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 10

->select (DB::raw ('count (id)')) 加上这个也不行的

5年前 评论

为什么说 count(*) 影响性能?

5年前 评论
Epona 5年前
Epona

查看了下源码,是不可以的,代码中直接写死了 count(*)

//Illuminate\Database\Eloquent\Relations\Relation
    public function getRelationExistenceCountQuery(Builder $query, Builder $parentQuery)
    {
        return $this->getRelationExistenceQuery(
            $query, $parentQuery, new Expression('count(*)')
        )->setBindings([], 'select');
    }
5年前 评论
charming-xiaoxia (楼主) 5年前

可以看看官方文档 https://dev.mysql.com/doc/refman/8.0/en/gr...

InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) operations in the same way. There is no performance difference.

For MyISAM tables, COUNT(*) is optimized to return very quickly if the SELECT retrieves from one table, no other columns are retrieved, and there is no WHERE clause.

对于 InnoDB 来说,COUNT(*)COUNT(1) 是完全一致的,并没有什么不同

对于 MyISAM 来说,如果没有带上 WHERE 语句,则会非常快的返回结果,比如:

mysql> SELECT COUNT(*) FROM student;

这种优化也仅仅适用于 MyISAM,因为这种存储引擎存储了精确的行数。

个人经验而言,我认为是没有什么差别的

count(*), count(1), count(id)

5年前 评论
charming-xiaoxia (楼主) 5年前

简单的 count(*) 应该不会花这么多时间吧 ,可能你的是 InnoDB 因为 stackoverflow 上有人是这么说的 COUNT () with InnoDB is slower than COUNT(ID) because InnoDB doesn’t cache the row count. :joy:我没验证过就是了。我在 MyISAM 下测试的结果:加上 where,count () ,count (1) 和 count (索引字段) 是一样的速度,where 条件有索引也比没索引快,count(id) 跟其他没索引的字段一样慢,count 一个空字段就更慢了。所以我想还是 count( *),再给 where 字段加合适的索引
file

file

file

5年前 评论
CrazyZard

file

file
别再说什么百万 innodb 表 count (*) 数据查询慢了 4 千万的数据量也就是几十秒的概念

5年前 评论
FMW 5年前
CrazyZard (作者) 5年前
FMW 5年前

@charming-xiaoxia  explain 下。感觉你这个肯定有问题。

5年前 评论

同感,我 10 万条的一个测试表,有个字段是 json,大概 50kB 一个 json,count(*) 要十多秒。。。后来删掉这个 json 字段分其他表存储之后,count(*) 只需要最多 30 毫秒,芜湖起飞!
(count(*) 的 SQL 执行倒是不慢,但是模型加载会很慢)

4年前 评论
charming-xiaoxia (楼主) 4年前
Q1ao (作者) 4年前
charming-xiaoxia (楼主) 4年前
charming-xiaoxia (楼主) 4年前
66

没区别呀 他们命中的 rows 都是相同数量

select count(*)

select count(id)

file

file
实查效率也没有区别 200W 的表

Laravel

4年前 评论