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

时间:2022-08-23 09:10:58

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;