简体   繁体   English

如何计算与查询匹配的行数,但只返回SQL中的子集?

[英]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. 检查使用SQL_CALC_FOUND_ROWS。 You add that to your select in the first query and then just call SELECT FOUND_ROWS() after. 您可以在第一个查询中将其添加到select中,然后在之后调用SELECT FOUND_ROWS()。 You can read more about it here: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows . 您可以在此处阅读更多相关信息: 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. 是的,这比运行搜索查询2次更有效。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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