26

In the following query I get syntax error:

SELECT <property1>, <property2>
FROM <table1> 
ORDER BY <condition> LIMIT 1
UNION  ALL
SELECT <property1>, <property2>
FROM <table2> 
WHERE <condition> ORDER BY <condition> LIMIT 1;

syntax error at or near "UNION" LINE 4: UNION ALL

Each of the SELECT stand alone executes fine. My guess is about the ORDER BY... LIMIT 1 maybe?

michael
  • 3,835
  • 14
  • 53
  • 90

3 Answers3

47

Wrap each query with ():

(SELECT <property1>, <property2>
FROM <table1> 
ORDER BY <condition> LIMIT 1)
UNION  ALL
(SELECT <property1>, <property2>
FROM <table2> 
WHERE <condition> ORDER BY <condition> LIMIT 1);

SqlFiddleDemo

You could also order final query:

(SELECT 'a' AS col
ORDER BY col LIMIT 1)
UNION ALL 
(SELECT 'b' AS col
ORDER BY col  LIMIT 1)
ORDER BY  col DESC
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
9

The first answer of @lad2025 is correct,
but the generalization just under is not correct because must be the whole condition, desc clause included.

This is the correct code :

(SELECT 'a' AS col
ORDER BY col DESC LIMIT 1)
UNION ALL
(SELECT 'b' AS col
ORDER BY col DESC LIMIT 1)
ORDER BY col DESC LIMIT 1

otherwise you select only le highest of the two lowest col of select 1 and select 2 (if any)
(and not the highest of all the cols)
and you must not forget the LIMIT 1 at the end too.

zx485
  • 28,498
  • 28
  • 50
  • 59
herve-guerin
  • 2,827
  • 20
  • 25
0
SELECT <property1>, <property2>
FROM <table1> 
LIMIT 1
UNION  ALL
SELECT <property1>, <property2>
FROM <table2> 
WHERE <condition> ORDER BY <condition> LIMIT 1;