PHP FOUND_ROWS和COUNT在同一个SELECT中

时间:2014-04-26 09:02:19

标签: php mysql

我有这段代码:

$sql = "SELECT FOUND_ROWS() AS totalRows, COUNT(*) AS totalRefunds FROM table WHERE result = 'refunded'";
$totalRows = $conn->query( $sql )->fetch();
$totalRefunds = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0], "totalRefunds" => $totalRefunds[0] ) );

我想要totalRows = 7和totalRefunds = 1但是上面两者都返回0。如果我删除了FOUND_ROWS()COUNT(*)语句,那么另一个语句就可以了。我猜测SELECT中有错误,但不确定它是什么。或者其他可能是错的???

提前致谢。

3 个答案:

答案 0 :(得分:0)

要获取此行计数,请在SELECT语句中包含SQL_CALC_FOUND_ROWS选项,然后再调用FOUND_ROWS()

$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM  table WHERE result = 'refunded'";

然后SELECT FOUND_ROWS()

答案 1 :(得分:0)

试试这种方式。假设您在运行此

之前使用SQL_CALC_FOUND_ROWS运行查询
SELECT (@variable := FOUND_ROWS()) AS totalRows, COUNT(*) AS totalRefunds 
FROM table WHERE result = 'refunded'

答案 2 :(得分:0)

FOUND_ROWS()用于计算行,就像忽略LIMIT一样。它不会将总行追加到其他查询结果中(除非您全部选择它们,但如果您只需要计数则没有意义)。如果您只想要这些信息,请执行此操作:

$sql = "SELECT COUNT(*) as totalRows FROM table";
$totalRows = $conn->query( $sql )->fetch();
$sql = "SELECT COUNT(*) as totalRefunds FROM table WHERE result = 'refunded'";
$totalRefunds = $conn->query( $sql )->fetch();

其他方式(但不同的上下文)是使用GROUP BY将计数拆分为所有“结果”列类型(退款/未退款/其他..),以便可以获得总行数作为单个计数的总和返回。