Skip to content

Commit 6f51a04

Browse files
committed
- Fixed UNION-behavior with OrderBy and GroupBy
1 parent a6368a0 commit 6f51a04

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

src/Builder/Traits/UnionBuilder.php

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,23 @@ public function unionAll($query) {
3030
* @return string
3131
*/
3232
protected function buildUnions($query) {
33-
$qaueries = [$query];
33+
$wrap = function ($query) {
34+
$query = trim($query);
35+
$query = join("\n\t", explode("\n", $query));
36+
return sprintf("(\n\t%s\n)", $query);
37+
};
38+
$queries = [$wrap($query)];
3439
foreach($this->unions as $unionQuery) {
3540
if($unionQuery[0] === 'ALL') {
36-
$qaueries[] = 'UNION ALL';
41+
$queries[] = 'UNION ALL';
3742
} else {
38-
$qaueries[] = 'UNION';
43+
$queries[] = 'UNION';
3944
}
40-
$qaueries[] = $unionQuery[1];
45+
$queries[] = $wrap($unionQuery[1]);
4146
}
42-
return join("\n", $qaueries);
47+
if(count($queries) > 1) {
48+
return join(" ", $queries);
49+
}
50+
return $query;
4351
}
4452
}

tests/Builder/SelectTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,6 @@ public function testSubselectUnion() {
190190
->where('t1.id > 10')
191191
->asString();
192192

193-
$this->assertEquals("SELECT\n\tt1.field\nFROM\n\ttest1 t1\nINNER JOIN\n\ttest2 t2 ON t1.id=t2.id\nWHERE\n\t(t1.id > 10)\n\nUNION\nSELECT\n\tt1.field\nFROM\n\ttest1 t1\nINNER JOIN\n\ttest2 t2 ON t1.id=t2.id\nWHERE\n\t(t1.id > 10)\n", $query);
193+
$this->assertEquals("(\n\tSELECT\n\t\tt1.field\n\tFROM\n\t\ttest1 t1\n\tINNER JOIN\n\t\ttest2 t2 ON t1.id=t2.id\n\tWHERE\n\t\t(t1.id > 10)\n) UNION (\n\tSELECT\n\t\tt1.field\n\tFROM\n\t\ttest1 t1\n\tINNER JOIN\n\t\ttest2 t2 ON t1.id=t2.id\n\tWHERE\n\t\t(t1.id > 10)\n)", $query);
194194
}
195195
}

0 commit comments

Comments
 (0)