SQL和PHP - 哪个mysql_num_rows()或“select count()”更快?

2022-08-30 14:55:22

我只是想知道哪种方法是最有效的,如果我真的只是想得到表中的行数。

$res = mysql_query("SELECT count(*) as `number` FROM `table1`");
$count = mysql_fetch_result($res,0,'number');

$res = mysql_query("SELECT `ID` FROM `table1`");
$count = mysql_num_rows($res);

有人对此做过任何像样的测试吗?


答案 1

mysql_query() 在返回之前将所有结果记录从 MySQL 传输到 php pcrocess 中(与 mysql_unbufferd_query()) 不同)。仅此一项就会使mysql_num_rows()版本变慢。

此外,对于某些引擎(如MyISAM),MySQL可以从表的索引中提供Count(*)请求,而不会命中实际数据。另一方面,A会导致全表扫描,MySQL必须读取每个数据集。SELECT * FROM foo


答案 2

在行数超过 2300000 的数据库中进行测试,类型:InnoDB,大小接近 1 GiB,使用 xhprof

测试1:

    ....SELECT COUNT(id) as cnt FROM $table_name....;
       row= mysqli_fetch_assoc($res2);
   echo $row['cnt'];
        //result1:
        1,144,106
        1,230,576
        1,173,449
        1,163,163
        1,218,992

测试2:

....SELECT COUNT(*) as cnt FROM $table_name....;
       row= mysqli_fetch_assoc($res2);
   echo $row['cnt'];
//result2:
1,120,253
1,118,243   
1,118,852
1,092,419
1,081,316

测试3:

 ....SELECT * FROM $table_name....;
    echo mysqli_num_rows($res2);
    //result3:
7,212,476
6,530,615
7,014,546
7,169,629
7,295,878

测试4:

     ....SELECT * FROM $table_name....;
        echo mysqli_num_rows($res2);
        //result4:
1,441,228
1,671,616
1,483,050
1,446,315
1,647,019

结论:最快的方法是在测试中2:

....SELECT COUNT(*) as cnt FROM $table_name....;
       row= mysqli_fetch_assoc($res2);
   echo $row['cnt'];

推荐