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?
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.
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).
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.
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 */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With