Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNION after ORDER BY and LIMIT

Tags:

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?

like image 985
lvil Avatar asked Jun 01 '11 08:06

lvil


People also ask

Can we use UNION after ORDER BY?

Union is a type of operator in MySQL. We can use ORDER BY with this to filter records. Use UNION if you want to select rows one after the other from several tables or several sets of rows from a single table all as a single result set. Let us see an example.

Can we use limit with UNION?

Beginning with MySQL 8.0. 19, you can use ORDER BY and LIMIT with TABLE in unions in the same way as just shown, bearing in mind that TABLE does not support a WHERE clause. This kind of ORDER BY cannot use column references that include a table name (that is, names in tbl_name . col_name format).

How do you use limit after ORDER BY?

ORDER BY LIMIT is used to get rows from table in sorting order either in ascending or descending order and to limit rows in result-set. ORDER BY LIMIT is not supported in all databases.


1 Answers

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 */ 
like image 159
Salman A Avatar answered Sep 19 '22 12:09

Salman A