diff --git a/model/SQLQuery.php b/model/SQLQuery.php index 44c4f5d0a..6e49d9b7f 100644 --- a/model/SQLQuery.php +++ b/model/SQLQuery.php @@ -1066,10 +1066,20 @@ class SQLQuery { * @param $alias An optional alias for the aggregate column. */ public function aggregate($column, $alias = null) { - $clone = clone $this; - $clone->setLimit($this->limit); - $clone->setOrderBy($this->orderby); + + // don't set an ORDER BY clause if no limit has been set. It doesn't make + // sense to add an ORDER BY if there is no limit, and it will break + // queries to databases like MSSQL if you do so. Note that the reason + // this came up is because DataQuery::initialiseQuery() introduces + // a default sort. + if($this->limit) { + $clone->setLimit($this->limit); + $clone->setOrderBy($this->orderby); + } else { + $clone->setOrderBy(array()); + } + $clone->setGroupBy($this->groupby); if($alias) { $clone->setSelect(array()); @@ -1077,7 +1087,6 @@ class SQLQuery { } else { $clone->setSelect($column); } - return $clone; } diff --git a/tests/model/SQLQueryTest.php b/tests/model/SQLQueryTest.php index 956fa244c..d6cfe174a 100755 --- a/tests/model/SQLQueryTest.php +++ b/tests/model/SQLQueryTest.php @@ -414,6 +414,31 @@ class SQLQueryTest extends SapphireTest { $this->assertEquals(array(2), $result->column('cnt')); } + /** + * Tests that an ORDER BY is only added if a LIMIT is set. + */ + public function testAggregateNoOrderByIfNoLimit() { + $query = new SQLQuery(); + $query->setFrom('"SQLQueryTest_DO"'); + $query->setOrderBy('Common'); + $query->setLimit(array()); + + $aggregate = $query->aggregate('MAX("ID")'); + $limit = $aggregate->getLimit(); + $this->assertEquals(array(), $aggregate->getOrderBy()); + $this->assertEquals(array(), $limit); + + $query = new SQLQuery(); + $query->setFrom('"SQLQueryTest_DO"'); + $query->setOrderBy('Common'); + $query->setLimit(2); + + $aggregate = $query->aggregate('MAX("ID")'); + $limit = $aggregate->getLimit(); + $this->assertEquals(array('Common' => 'ASC'), $aggregate->getOrderBy()); + $this->assertEquals(array('start' => 0, 'limit' => 2), $limit); + } + /** * Test that "_SortColumn0" is added for an aggregate in the ORDER BY * clause, in combination with a LIMIT and GROUP BY clause.