diff --git a/library/Icinga/Data/BaseQuery.php b/library/Icinga/Data/BaseQuery.php index 061ff0f46..4e6192315 100644 --- a/library/Icinga/Data/BaseQuery.php +++ b/library/Icinga/Data/BaseQuery.php @@ -59,6 +59,13 @@ abstract class BaseQuery implements Filterable */ private $limitOffset; + /** + * Whether its a distinct query or not + * + * @var bool + */ + private $distinct = false; + /** * The backend independent filter to use for this query * @@ -294,6 +301,30 @@ abstract class BaseQuery implements Filterable return $this; } + /** + * Return only distinct results + * + * @param bool $distinct Whether the query should be distinct or not + * + * @return BaseQuery + */ + public function distinct($distinct = true) + { + $this->distinct = $distinct; + + return $this; + } + + /** + * Determine whether this query returns only distinct results + * + * @return bool True in case its a distinct query otherwise false + */ + public function isDistinct() + { + return $this->distinct; + } + /** * Determine whether this query will be ordered explicitly * diff --git a/library/Icinga/Data/Db/Query.php b/library/Icinga/Data/Db/Query.php index 3dead6476..3ee381ff5 100644 --- a/library/Icinga/Data/Db/Query.php +++ b/library/Icinga/Data/Db/Query.php @@ -85,6 +85,14 @@ class Query extends BaseQuery if ($this->baseQuery !== null) { $this->baseQuery = clone $this->baseQuery; } + + if ($this->selectQuery !== null) { + $this->selectQuery = clone $this->selectQuery; + } + + if ($this->countQuery !== null) { + $this->countQuery = clone $this->countQuery; + } } /** @@ -148,6 +156,7 @@ class Query extends BaseQuery { $this->selectQuery = clone($this->baseQuery); $this->selectQuery->columns($this->getColumns()); + $this->selectQuery->distinct($this->isDistinct()); if ($this->hasOrder()) { foreach ($this->getOrderColumns() as $col) { $this->selectQuery->order( @@ -200,8 +209,8 @@ class Query extends BaseQuery */ private function createCountQuery() { - if ($this->useSubqueryCount) { - $this->countQuery = $this->createCountAsSubquery(); + if ($this->isDistinct() || $this->useSubqueryCount) { + $this->countQuery = $this->createCountAsSubQuery(); } else { $this->countQuery = $this->createCustomCountQuery(); }