简体   繁体   English

计算表中行的最有效方法是什么?

[英]What's the most efficient way to count rows in a table?

Is it more efficient to use: 使用效率更高:

$sql = 'SELECT COUNT(*) AS count FROM users';
$odbcResult = OdbcExec($sql);
@odbc_fetch_row($odbcResult);
$count = @odbc_result($odbcResult, 'count');

or to use: 或使用:

$sql = 'SELECT * FROM users';
$odbcResult = OdbcExec($sql);    
$count = odbc_num_rows($odbcResult);

The former. 前者。 The server is doing the work. 服务器正在做这项工作。 It may already know the answer without counting, 它可能已经知道答案而不计算,

The later requires all the rows to be returned to your program over the network (and into memory). 后者要求通过网络(并进入内存)将所有行返回到程序。

$sql = 'SELECT COUNT(id) AS count FROM users';
$odbcResult = OdbcExec($sql);
@odbc_fetch_row($odbcResult);
$count = @odbc_result($odbcResult, 'count');

or some other index field besides id. 或者除了id之外的其他索引字段。 Its a little faster than COUNT(*), but the count method is the way to go. 它比COUNT(*)快一点,但count方法是要走的路。 If you need to do something with the results, method 2 is faster, but only needing count this is the one you want. 如果您需要对结果执行某些操作,方法2会更快,但只需要计算这个就是您想要的。

-edit- Added keyword of index before field. -edit-在字段之前添加了索引的关键字。 True comment below, made the assumption that there was an id index column (should have an index somewhere at any rate) 下面的真实评论,假设有一个id索引列(应该以任何速率在某个地方有一个索引)

使用x> = 6的10 ^ x元素填充表格并查看所需的时间。

The first method is definitely faster. 第一种方法肯定更快。 But COUNT(id) being faster than COUNT(*) - questionable. 但是COUNT(id)比COUNT(*)快 - 有问题。 They usually are exactly the same, and there are cases when COUNT(id) is actually slower (see: http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/ ) 它们通常完全相同,并且有些情况下COUNT(id)实际上更慢(参见: http//www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/

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

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