简体   繁体   中英

Fastest way to count number of rows in MySQL database in Laravel?

I can think of a couple ways to count the number of rows in a table with Laravel (version 3).

DB::table('threads')->count();
Threads::count();
Threads::max('id');
DB::table('threads')->max('id);
DB::query('SELECT COUNT(*) FROM threads;');

Are any of these notably faster than the others? Is there any one fastest way to run this query? Later on it's going to be part of an expression: ceil(DB::table('threads')->count() / $threads_per_page); and it's executed on every page load so it's good to be optimized.

Database/table is MySQL and the InnoDB engine.

MAX(ID) is not the same as counting rows, so that rules out two of five alternatives.

And then it is your task to actually do a performance comparison between the remaining three methods to get the count. I'd think that actually executing an SQL statement directly might remove plenty of unnecessary ORM-layer overhead and be actually faster, but this would be premature optimization unless proven by facts.

DB::table('threads')->count();
Threads::count();
DB::query('SELECT COUNT(*) FROM threads;');

I was looking for the same thing. These 3 results are exactly the same query I tested it (You can watch this with laravel debugbar). Laravel perform "SELECT COUNT(*) as aggregate FROM threads"; It's already optimised with eloquent, but if you do ->get()->count() it's not optimised ! No performance difference with Threads::count();

Max('id') is totally different as it output the max id, it will never count the number of rows.

我不认为这真的很重要..只是在您的代码中保持一致..以任何方式都不需要在evey页面加载时运行该查询..使用一些缓存来缓存该数字..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM