gpt4 book ai didi

php - 如何获取 GROUP BY 查询的总行数?

转载 作者:IT王子 更新时间:2023-10-29 00:00:51 25 4
gpt4 key购买 nike

来自 PDO 手册:

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

我是最近才发现的。我刚刚将我的数据库抽象层更改为不再使用 SELECT COUNT(1) ...,因为只查询实际行然后计算结果会更有效率。而现在 PDO 不支持了!?

我不为 MySQL 和 PgSQL 使用 PDO,但我为 SQLite 使用。有没有办法(不完全改变 dbal)在 PDO 中计算这样的行?在 MySQL 中,这将是这样的:

$q = $db->query('SELECT a, b, c FROM tbl WHERE oele = 2 GROUP BY boele');
$rows = $q->num_rows;
// and now use $q to get actual data

使用 MySQLi 和 PgSQL 驱动程序,这是可能的。所有 PDO 都不是!?

PS。我最初的解决方案是扩展 SQLResult->count 方法(我自己的)以用 SELECT COUNT(1) FROM 替换 SELECT ... FROM 并返回该数字(非常低效,但仅适用于 SQLite PDO)。但这还不够好,因为在上面的示例查询中是一个 GROUP BY,它会改变 COUNT(1) 的含义/功能。

最佳答案

这是给你的解决方案

$sql="SELECT count(*) FROM [tablename] WHERE key == ? ";
$sth = $this->db->prepare($sql);
$sth->execute(array($key));
$rows = $sth->fetch(PDO::FETCH_NUM);
echo $rows[0];

关于php - 如何获取 GROUP BY 查询的总行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6041886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com