SQL Union All with order by和limit(Postgresql)

时间:2016-05-20 17:14:23

标签: sql postgresql union union-all

在以下查询中,我收到语法错误:

SELECT <property1>, <property2>
FROM <table1> 
ORDER BY <condition> LIMIT 1
UNION  ALL
SELECT <property1>, <property2>
FROM <table2> 
WHERE <condition> ORDER BY <condition> LIMIT 1;
  “UNION”或附近的

语法错误   第4行:UNION ALL

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

3 个答案:

答案 0 :(得分:11)

使用()包装每个查询:

(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

答案 1 :(得分:1)

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

答案 2 :(得分: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

否则,您只选择选择1的两个最低色列中的最高色,并选择2(如果有)
(而不是所有cols中最高的)
你也不能忘记最后的LIMIT 1。