MYSQL中统计查询结果总行数的便捷方法省去count(*)
程序员文章站
2024-03-31 11:33:58
mysql的关键词 : sql_calc_found_rows 查看手册后发现此关键词的作用是在查询时统计满足过滤条件后的结果的总数(不受 limit 的限制) 例如: 复...
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;
}
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;
}
上一篇: AsyncTask的三个属性值和四个步骤
下一篇: pt-kill 常用杀进程参数介绍