UNION after ORDER BY and LIMIT

lvil picture lvil · Jun 1, 2011 · Viewed 18.7k times · Source

My goal is to execute two different queries and then combine them.
My code is:

SELECT * FROM some tables WHERE ... ORDER BY field1 LIMIT 0,1 
UNION   
SELECT * FROM some tables WHERE ...

I get the following error:

#1221 - Incorrect usage of UNION and ORDER BY

It is important that ORDER BY is only for the first query. How can I perform this task?

Answer

Salman A picture Salman A · Jun 1, 2011

You can use parenthesis to allow the use of ORDER/LIMIT on individual queries:

(SELECT * FROM some tables WHERE ... ORDER BY field1 LIMIT 0, 1)
UNION   
(SELECT * FROM some tables WHERE ...)
ORDER BY 1   /* optional -- applies to the UNIONed result */
LIMIT 0, 100 /* optional -- applies to the UNIONed result */