framework icon indicating copy to clipboard operation
framework copied to clipboard

UNION queries missing parentheses

Open andy3rdworld opened this issue 13 years ago • 28 comments

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;
}

andy3rdworld avatar Oct 16 '13 05:10 andy3rdworld

Fixed.

taylorotwell avatar Oct 29 '13 18:10 taylorotwell

I think bug still exists in version 5.0.X. Although I'm using PostgreSQL...

$cols = ['id', 'name', 'date', 'description'];
$today = date('Y-m-d');

$before = DB::table('calendar')->select($cols)->where('date', '<', $today)->orderBy('date', 'DESC')->limit(5);
$after = DB::table('calendar')->select($cols)->where('date', '>=', $today)->orderBy('date', 'ASC')->limit(5);

$timeline = $after->union($before)->get();

QuerException:

SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "union"
LINE 1: ...r" where "date" >= $1 order by "date" asc limit 5 union sele...
^ (SQL: select "id", "name", "date", "description" from "calendar" where "date" >= 2015-06-30 order by "date" asc limit 5 union select "id", "name", "date", "description" from "calendar" where "date" < 2015-06-30 order by "date" desc limit 5)

As you can see there is no parentheses...

adam-boduch avatar Jun 30 '15 19:06 adam-boduch

I think bug still exists in version 5.0.X. Althought I'm using PostgreSQL...

5.0 isn't supported.

GrahamCampbell avatar Jun 30 '15 19:06 GrahamCampbell

I think bug still exists in version 5.0.X. Althought I'm using PostgreSQL...

5.2.X isn't supported either.

manithchhuon avatar May 26 '16 02:05 manithchhuon

Still exists on 5.3

gtapps avatar Nov 04 '16 02:11 gtapps

Still exists on 5.6

jorgevilaca82 avatar Jun 06 '18 22:06 jorgevilaca82

Still exists in 5.6 👎

rockfridrich avatar Jul 13 '18 23:07 rockfridrich

Still exists in 5.8 . Any solution?

robsontenorio avatar Jan 12 '19 18:01 robsontenorio

@staudenmeir any chance you can help check if this still exists for 5.7?

driesvints avatar Jan 14 '19 12:01 driesvints

@driesvints Yes, this is still an issue on PostgreSQL and SQL Server. I'll take care of it.

staudenmeir avatar Jan 14 '19 14:01 staudenmeir

@staudenmeir thanks man 👍

driesvints avatar Jan 14 '19 21:01 driesvints

@staudenmeir are there any updates to this? Is the fix going to be similar to what had been requested in https://github.com/laravel/framework/issues/5457 ?

celloman avatar Feb 06 '19 23:02 celloman

@celloman I'm still working on it. Are you affected by #5457?

staudenmeir avatar Feb 07 '19 01:02 staudenmeir

@staudenmeir Meh, not too much. I was having a syntax issue due to extra parentheses using union. After I asked that question I ended up finding a workaround by using a builder with a where closure to group a whereIn and an orWhereIn to accomplish the same result (though the resulting sql is not as pretty and I don't know if it is equal performance-wise since there is more nesting in the sql)...

Mostly now I'm wondering if this fix will address the same issue I was seeing... I'll just follow along to see if I can refactor back to a union at some point, thanks!

celloman avatar Feb 07 '19 16:02 celloman

I'm asking because I can't reproduce #5457.

What query caused your syntax error?

staudenmeir avatar Feb 07 '19 17:02 staudenmeir

@staudenmeir ah I see. The query in question was something like the following:

select * from item where item.user_id in ((select users.id from users inner join ( select users.id as user_id from users where (users.id = 1) and users.client_id= 1 and users.deleted_at is null and users.state = 1 order by users.id asc ) as rule_query on users.id = rule_query.user_id where users.client_id = 1) union (select users.id from users where users.points > 100))

which works when you remove the parentheses around the statements being unioned together, like hte following:

select * from item where item.user_id in (select users.id from users inner join ( select users.id as user_id from users where (users.id = 1) and users.client_id= 1 and users.deleted_at is null and users.state = 1 order by users.id asc ) as rule_query on users.id = rule_query.user_id where users.client_id = 1 union select users.id from users where users.points > 100)

Note: I am running MySql (Percona 5.7.22)

celloman avatar Feb 08 '19 21:02 celloman

What query builder generates this SQL?

staudenmeir avatar Feb 08 '19 22:02 staudenmeir

@staudenmeir A user model is what is being union'ed together (selecting only ids under various conditions and then unioning those together), and then the resulting builder from this union'ing is passed to some other model (depending on the need) using a whereIn('user_id', <unioned_user_builder_here>) type of thing

celloman avatar Feb 11 '19 22:02 celloman

Can you provide a simple example of a query builder that causes the syntax error described in #5457?

staudenmeir avatar Feb 11 '19 23:02 staudenmeir

App\User::withoutGlobalScopes()->select('users.id')->whereIn('users.id', App\User::select('users.id')->withoutGlobalScopes()->where('id', 1)->union(App\User::select('users.id')->withoutGlobalScopes()->where('id', 2)))->get()

Though this query obviously doesn't accomplish much, this is about as simple of an example as I can think of (the withoutGlobalScopes calls probably aren't necessary, I was just trying to ensure minimal sql output).

produces: select `users`.`id` from `users` where `users`.`id` in ((select `users`.`id` from `users` where `id` = 1) union (select `users`.`id` from `users` where `id` = 2))

celloman avatar Feb 15 '19 20:02 celloman