SQL Union All with order by and limit (Postgresql)

SQL Union All with order by and limit (Postgresql)

在以下查询中出现语法错误:

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

每个 SELECT 独立执行都很好。我的猜测是关于 ORDER BY... LIMIT 1 也许?

()包装每个查询:

(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

您还可以订购最终查询:

(SELECT 'a' AS col
ORDER BY col LIMIT 1)
UNION ALL 
(SELECT 'b' AS col
ORDER BY col  LIMIT 1)
ORDER BY  col DESC
SELECT <property1>, <property2>
FROM <table1> 
LIMIT 1
UNION  ALL
SELECT <property1>, <property2>
FROM <table2> 
WHERE <condition> ORDER BY <condition> LIMIT 1;

@lad2025第一个回答正确,
但是下面的概括是不正确的,因为必须是整个条件,包括 desc 子句。

这是正确的代码:

(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

否则你 select 只在 select 1 和 select 2(如果有)
的两个最低列中最高 (而不是所有列中最高的)
最后也不要忘记LIMIT 1。