我想知道如何使用 LIMIT
将SELECT FOUND_ROWS()
包含在现有查询中,或者是否有更好的方法可以在没有LIMIT
的情况下获取总行数。
//SELECT * just for question
$q = $this->db->mysqli->prepare("SELECT SQL_CALC_FOUND_ROWS *
FROM countries_ship c
JOIN items i
ON c.item_id = i.id
JOIN item_expire e
ON c.item_id = e.item_id
JOIN users u
ON i.user_id = u.id
LEFT JOIN bids b
ON i.id = b.item_id
LEFT JOIN publishers p
ON i.item_publisher = p.id
LEFT JOIN tags_rel tr
ON c.item_id = tr.item_id
JOIN tags t
ON t.id = tr.tag_id
LEFT JOIN countries co
ON i.item_location = co.id
WHERE ".$where."
GROUP BY i.id ORDER BY ".$order." ".$limit."");
$count_rows = $this->db->mysqli->query("SELECT FOUND_ROWS()");
/* return of var_dump($count_rows);
object(mysqli_result)#74 (5) {
["current_field"]=>
int(0)
["field_count"]=>
int(1)
["lengths"]=>
NULL
["num_rows"]=>
int(1)
["type"]=>
int(0)
}
*/
$prep = join("", $prep);
call_user_func_array('mysqli_stmt_bind_param', array_merge ( array($q, $prep), $this->helperClass->valRef($ref) ) );
$q->execute();
$rows = $this->helperClass->bindResults($q);
$q->close();
return $rows;
不确定这是否是 100% 有效的,但这就是我解决问题的方式。
- 更改了查询
SELECT SQL_CALC_FOUND_ROWS
的开头 - 创建新阵列 -
$resArray = array()
按照建议移动了第二个查询,并将两个结果都添加到
$resArray
。$q->execute(); $rows = $this->helperClass->bindResults($q); $q->close(); $count_rows = $this->db->mysqli->query("SELECT FOUND_ROWS()"); $count = mysqli_fetch_assoc($count_rows); $resArray[] = $count; $resArray[] = $rows; return $resArray;
虽然我可能是错的,但似乎如果您只想获取符合您条件的行数,您应该像这样使用 SQL 的计数聚合函数:
SELECT
i.id,
count(*)
FROM
countries_ship c
JOIN items i
ON c.item_id = i.id
JOIN item_expire e
ON c.item_id = e.item_id
JOIN users u
ON i.user_id = u.id
LEFT JOIN bids b
ON i.id = b.item_id
LEFT JOIN publishers p
ON i.item_publisher = p.id
LEFT JOIN tags_rel tr
ON c.item_id = tr.item_id
JOIN tags t
ON t.id = tr.tag_id
LEFT JOIN countries co
ON i.item_location = co.id
WHERE
".$where."
GROUP BY
i.id
另一方面,如果您想以一种可以分页的方式获取计数和所有详细信息,最好只运行两个查询 - 一个用于聚合计数,另一个用于有限的结果。
编辑:我已将 i.id 分组保留在查询中,因为它将为您提供每 i.id 匹配行的计数。如果您只想要 TOTAL 计数,则可以将其从 select 子句和分组依据中删除,从而完全删除组。
您在SQL_CALC_FOUND_ROWS
的正确轨道上,您只需要移动到执行查询的位置即可计算资源。因为它仅在运行原始查询后有效。因此,$count_rows = $this->db->mysqli->query("SELECT FOUND_ROWS()");
移至$q->execute();
之后