简体   繁体   中英

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

At present, 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.

根据mysqlperformanceblog的MySQL专家基准测试运行两个单独的查询可能比在一个查询中组合这两个查询更快

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM