framework: UNION queries missing parentheses
For MySQL UNIONs, when an ORDER BY is included, each statement must be surrounded by parentheses like so:
(SELECT * FROM table_name WHERE col1 = ‘some value’ ORDER BY col2 DESC ) UNION ALL (SELECT * FROM table_name WHERE col1 = ‘some other value’ ORDER BY col2 DESC );
If parentheses are missing you’ll get the following error: SQLSTATE[HY000]: General error: 1221 Incorrect usage of UNION and ORDER BY…
Currently the query builder does not appear to include these parentheses:
protected function compileUnions(Builder $query) { $sql = ‘’;
foreach ($query->unions as $union)
{
$joiner = $union['all'] ? 'union all ' : 'union ';
$sql = $joiner.$union['query']->toSql();
}
return $sql;
}
About this issue
- Original URL
- State: closed
- Created 11 years ago
- Comments: 28 (15 by maintainers)
Still exists in 5.6 👎
Still exists on 5.3
@bhuvidya We can’t fix that. Some
UNIONqueries require these parentheses.@driesvints The issue can be closed. With #29496, we now wrap
UNIONsubqueries on all databases.@driesvints Partially, it’s still an issue on SQL Server. I’m working on that.
Still exists on 5.6
5.2.X isn’t supported either.