MySQL count(”欄位”) vs mysql_num_rows 速度?

在 FreeBSD ports 裡面還沒看到 chinese/phpbb3 的 ports,目前只有 chinsan 維護的 chinese/phpbb-tw ports,之前版本是 2.0.22 版本,後來我 commit 到 2.0.23 版本,不過 PHPBB 官網已經不再維護或者是開發 2.0.X 版本了,現在以 PHPBB3 為版本開發,也針對了 PHP6 跟 PHP 5 的相容性做了很大的改變,所以基本上如果在 2.0.X 版本加了很多外掛,那就沒辦法升級到 phpBB3 版本了,畢竟 code 實在改變太多了,找個時間把 chinese/phpbb3-tw commit 進去,不然也可以到 www/phpbb3 做安裝。

為什麼會提到 phpBB 呢,今天在 trace phpBB3 的 code,發現原本在 phpBB2 裡面有支援 mysql_num_rows function,用來讓程式可以取出 sql 的個數,不過在 phpBB3 竟然就把這個 function 拿掉了。

phpBB2 mysql4.php 程式:

function sql_numrows ( $query_id = 0 )
{
    if ( ! $query_id )
    {
        $query_id = $this -> query_result ;
    }

    return ( $query_id ) ? mysql_num_rows ( $query_id ) : false ;
}


這樣可以利用 $db->sql_numrows 取得回傳個數

/*
* 取得 sql 回傳個數
*/

$sql = "SELECT * FROM " . CONFIG_TABLE ;
$result = $db -> sql_query ( $sql ) ;
$all_list_count = $db -> sql_numrows ( $result ) ;

在 phpBB3 變成另外一個作法

/*
* 利用 coumt() 來取得個數
*/

$sql = "SELECT COUNT(config_name) AS num_configs FROM " . CONFIG_TABLE ;
$result = $db -> sql_query ( $sql ) ;
$all_list_count = (int ) $db -> sql_fetchfield ( 'num_configs' ) ;

於是我就想比較一下執行的速度:count(*)

$sql = "SELECT COUNT(config_name) AS num_configs
FROM "
. CONFIG_TABLE ;
$starttime = explode ( ' ' , microtime ( ) ) ;
$starttime = $starttime [ 1 ] + $starttime [ 0 ] ;
$result = $db -> sql_query ( $sql ) ;
$all_list_count = (int ) $db -> sql_fetchfield ( 'num_configs' ) ;
echo $all_list_count ;
$endtime = explode ( ' ' , microtime ( ) ) ;
$endtime = $endtime [ 1 ] + $endtime [ 0 ] ;
echo $endtime - $starttime ;
$db -> sql_freeresult ( $result ) ;

輸出結果:0.000408172607422

$sql = "SELECT *
FROM "
. CONFIG_TABLE ;
$starttime = explode ( ' ' , microtime ( ) ) ;
$starttime = $starttime [ 1 ] + $starttime [ 0 ] ;
$result = $db -> sql_query ( $sql ) ;
$row = $db -> sql_numrows ( $result ) ;
echo $row ;
$endtime = explode ( ' ' , microtime ( ) ) ;
$endtime = $endtime [ 1 ] + $endtime [ 0 ] ;
echo $endtime - $starttime ;
$db -> sql_freeresult ( $result ) ;

輸出結果:0.000455141067505

發現利用 count(*) 的速度比較快,這是自己發現的結論啦,至少 phpBB3 目前的作法是採用 count(*) 的方式下去解,而並非利用 mysql_num_rows 方式。^^

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值