From ef0af7ae9c129e8e12e9c3660d3d52114e9b7cf3 Mon Sep 17 00:00:00 2001 From: Guy Marriott Date: Wed, 17 Apr 2019 09:49:46 +1200 Subject: [PATCH] FIX Exists statements can't remove GROUP BY if there's a HAVING clause as it might rely on an aggregate --- src/ORM/DataQuery.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/ORM/DataQuery.php b/src/ORM/DataQuery.php index 3bc8996b8..6b6e2cd6c 100644 --- a/src/ORM/DataQuery.php +++ b/src/ORM/DataQuery.php @@ -466,12 +466,17 @@ class DataQuery $statement = $this->getFinalisedQuery(); $statement->setSelect('*'); - // Clear limit, distinct, grouping, and order as it's not relevant for an exists query + // Clear limit, distinct, and order as it's not relevant for an exists query $statement->setDistinct(false); $statement->setOrderBy(null); - $statement->setGroupBy(null); $statement->setLimit(null); + // We can remove grouping if there's no "having" that might be relying on an aggregate + $having = $statement->getHaving(); + if (empty($having)) { + $statement->setGroupBy(null); + } + // Wrap the whole thing in an "EXISTS" $sql = 'SELECT EXISTS(' . $statement->sql($params) . ')'; $result = DB::prepared_query($sql, $params);