问题描述

union 连接的两个sql 都包含 order

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

错误

ERROR:  syntax error at or near "union"
LINE 2: union all
        ^
********** 错误 **********

ERROR: syntax error at or near "union"
SQL 状态: 42601
字符:149

 

解决方法

我找了很多资料,试了很多方法,都不行,最后是这样解决的

(SELECT <property1>, <property2>
FROM <table1> 
ORDER BY <condition>)

UNION  ALL

(SELECT <property1>, <property2>
FROM <table2> 
WHERE <condition> ORDER BY <condition>);

注意必须是 union all,不能是 union。

 

 

 

参考资料:

https://stackoverflow.com/questions/37352296/sql-union-all-with-order-by-and-limit-postgresql