首页 >数据库 >mysql教程 >MYSQL中统计查询结果总行数的便捷方法省去count(*)_MySQL

MYSQL中统计查询结果总行数的便捷方法省去count(*)_MySQL

WBOY
WBOY原创
2016-06-01 13:25:19964浏览

bitsCN.com MYSQL的关键词 :
SQL_CALC_FOUND_ROWS
查看手册后发现此关键词的作用是在查询时统计满足过滤条件后的结果的总数(不受 Limit 的限制)

例如:

SELECT SQL_CALC_FOUND_ROWS tid FROM cdb_threads WHERE fid=14 LIMIT 1,10;

假设满足条件的有1000条,这里返回10条。
立即使用

SELECT found_rows() AS rowcount;

则返回的 rowcount 为1000;
这样节省了SELECT count(*) AS rowcount的重复查询,可以节省比较可观的时间。

以下是该放在在游味中的应用:

function mail_list_sent( $uid, $start ) {
// 注意SQL_CALC_FOUND_ROWS uid之间没有逗号
$query = "SELECT SQL_CALC_FOUND_ROWS uid, real_name, current_city, msg_uid, sender_flag, ".
"msg_title, msg_content FROM " . TT_DBTABLEPRE . "mailbox as mb1, " . TT_DBTABLEPRE .
"user as usr1 WHERE mb1.sender_id=usr1.uid AND mb1.sender_id=$uid AND sender_flag > 0 LIMIT $start, " . TT_PAGESIZE;
$mails = $this->db->fetch_all( $query );
//查询SELECT中满足条件的行数,与LIMIT子句无关
$max_count = $this->db->fetch_first( "SELECT found_rows() AS rowcount" );
$tmp['state_code'] = 200;
$tmp['info'] = "OK";
$tmp['list'] = $mails;
$data = json_encode( $tmp );
return $data;
}
bitsCN.com

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn