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

标签 php database sqlite pdo

来自 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/

相关文章:

ios - 在 iOS 应用程序中使用预构建的 sqlite 数据库

php - 在 xampp 上安装 cake php

php - 如何在wordpress中发送带附件的邮件?

php - 在 Apache 中的 PHP 脚本中使用 ZeroMQ

Android 用光标删除行

c# - SQLite 和 .NET 用户控件

php - 无法删除动态添加的 div(由旧 div 触发的事件)

mysql - 2 个外键引用 1 个主键

php - 如何在另一个php文件中使用fetch数组

database - 如何将应用程序包中的数据库文件放入库/应用程序支持/目录中?