Skip to content

Commit

Permalink
Optimizing count queries by not using a derived table when there is no
Browse files Browse the repository at this point in the history
group by nor distinct clause
  • Loading branch information
lorenzo committed Jan 24, 2014
1 parent b832136 commit 314ade7
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/ORM/Query.php
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -882,17 +882,27 @@ public function count() {
$query = clone $this; $query = clone $this;
$query->limit(null); $query->limit(null);
$query->offset(null); $query->offset(null);
$query->mapReduce(null, null, true);
$query->formatResults(null, true);
$counter = $this->_counter; $counter = $this->_counter;


if ($counter) { if ($counter) {
$query->counter(null); $query->counter(null);
return (int)$counter($query); 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 // Forcing at least one field to be selected
$query->select($query->newExpr()->add('1')); $query->select($query->newExpr()->add('1'));
$statement = $this->connection()->newQuery() $statement = $this->connection()->newQuery()
->select(['count' => $query->func()->count('*')]) ->select($count)
->from(['count_source' => $query]) ->from(['count_source' => $query])
->execute(); ->execute();
$result = $statement->fetch('assoc')['count']; $result = $statement->fetch('assoc')['count'];
Expand Down

0 comments on commit 314ade7

Please sign in to comment.