开发者

How can I count the number of rows that match a query, but only return a subset in SQL?

At present, 开发者_StackOverflow中文版I have this code:

$result = $db->prepare("SELECT * FROM `users` WHERE MATCH (`name`, `blurb`) AGAINST (:quer IN BOOLEAN MODE) LIMIT $rpage, $max_show;");
$result->execute(array(":quer" => $query));

$count = $db->prepare("SELECT COUNT(*) FROM `users` WHERE MATCH (`name`, `blurb`) AGAINST (:quer IN BOOLEAN MODE);");
$count->execute(array(":quer" => $query));

The first query grabs a bunch of rows from the table. The second one counts the rows that match the same criteria as the first, allowing for pagination.

Can I combine these two queries into one? And would it be more efficient?


check into using SQL_CALC_FOUND_ROWS. You add that to your select in the first query and then just call SELECT FOUND_ROWS() after. You can read more about it here: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows. and yes this would be more efficient than running the search query 2 times.


According to the benchmarks of the MySQL experts at mysqlperformanceblog, running two seperate queries will probably be faster than combining both in one query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜