Skip to content
Permalink
Browse files

Optimizing count queries by not using a derived table when there is no

group by nor distinct clause
  • Loading branch information...
lorenzo committed Jan 24, 2014
1 parent b832136 commit 314ade7e07f55c3eb9c6a0b612183aaf0d7dc3f0
Showing with 11 additions and 1 deletion.
  1. +11 −1 src/ORM/Query.php
@@ -882,17 +882,27 @@ public function count() {
$query = clone $this;
$query->limit(null);
$query->offset(null);
$query->mapReduce(null, null, true);
$query->formatResults(null, true);
$counter = $this->_counter;
if ($counter) {
$query->counter(null);
return (int)$counter($query);
}
$count = ['count' => $query->func()->count('*')];
if (!count($query->clause('group')) && !$query->clause('distinct')) {
return (int)$query
->select($count, true)
->hydrate(false)
->first()['count'];
}
// Forcing at least one field to be selected
$query->select($query->newExpr()->add('1'));
$statement = $this->connection()->newQuery()
->select(['count' => $query->func()->count('*')])
->select($count)
->from(['count_source' => $query])
->execute();
$result = $statement->fetch('assoc')['count'];

0 comments on commit 314ade7

Please sign in to comment.
You can’t perform that action at this time.