简体   繁体   English

在Laravel中计算MySQL数据库中行数的最快方法?

[英]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). 我可以想到几种方法来使用Laravel(版本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); 稍后它将成为表达式的一部分: 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. 数据库/表是MySQL和InnoDB引擎。

MAX(ID) is not the same as counting rows, so that rules out two of five alternatives. MAX(ID)与对行进行计数不同,因此排除了五种选择中的两种。

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. 我认为直接执行SQL语句可能会消除大量不必要的ORM层开销,并且实际上会更快,但这是过早的优化,除非经过事实证明。

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). 这3个结果与我测试过的查询完全相同(您可以使用laravel debugbar观看此查询)。 Laravel perform "SELECT COUNT(*) as aggregate FROM threads"; Laravel执行“ SELECT COUNT(*)作为FROM线程的聚合”; It's already optimised with eloquent, but if you do ->get()->count() it's not optimised ! 它已经雄辩地进行了优化,但是如果您执行-> get()-> count(),它就没有优化! No performance difference with Threads::count(); Threads :: count();没有性能差异

Max('id') is totally different as it output the max id, it will never count the number of rows. Max('id')完全不同,因为它输出最大id,它将永远不会计算行数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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