26

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?

Salman A
  • 262,204
  • 82
  • 430
  • 521
lvil
  • 4,326
  • 9
  • 48
  • 76

4 Answers4

36

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 */
Jesse
  • 8,605
  • 7
  • 47
  • 57
Salman A
  • 262,204
  • 82
  • 430
  • 521
11
SELECT * FROM (SELECT * FROM some tables WHERE ... ORDER BY field1 LIMIT 0,1) x
UNION ALL
SELECT * FROM some tables WHERE ...

Note the use of UNION ALL:

  • UNION removes duplicate rows from the result set and the DB orders all the rows before doing this (so the entire result set is sorted)
  • UNION ALL preserves both order and duplicates
Bohemian
  • 412,405
  • 93
  • 575
  • 722
4

just put everything in round brackets:

(SELECT * FROM table1 ORDER BY datetime  )
UNION   
(SELECT * FROM table2 ORDER BY datetime DESC)
luca
  • 36,606
  • 27
  • 86
  • 125
2
(SELECT user_id AS id FROM tbl_user)
UNION
(SELECT address_id AS id FROM tbl_address)
ORDER BY id ASC LIMIT 10
Sona Rijesh
  • 1,041
  • 7
  • 32
  • 62