postgresql “联合”处或附近的 SQL 语法错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24020078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:28:28  来源:igfitidea点击:

SQL syntax error at or near 'union'

sqlpostgresqlsql-order-byunion

提问by Padagomez

I have a small query, and a union to put another small query next to it. However, the union has a syntax error in it.

我有一个小查询和一个联合,可以在它旁边放置另一个小查询。但是,联合中有一个语法错误。

Select <column1>
      ,<column2>
From <Table1> 
<Some joins in there>
Where <conditions>
group by <column2>
order by <column2>

union

select <column2>
      ,<column3>
      ,<column4>
From <Table2>
<Some more joins here>
Where <conditions>
group by <column2>
order by <column2>

This is the Error I receive

这是我收到的错误

ERROR: Syntax error at or near 'union'

回答by Padagomez

I see what was wrong. You have to place the order by at the end of the query, and only at the end. It gave me an error because it thought the query had eneded.

我明白出了什么问题。您必须在查询的末尾下订单,并且只能在最后。它给了我一个错误,因为它认为查询已经完成。

Select <column1>
      ,<column2>
      ,<aggregate column3>
From <Table1> 
<Some joins in there>
Where <conditions>
group by <column2>, <column1>

union

select <column2>
      ,<column3>
      ,<aggregate column4>
From <Table2>
<Some more joins here>
Where <conditions>
group by <column2>, <column3>
order by <column2>

That did the trick.

这就是诀窍。

回答by Daniel Vérité

Short answer: (SELECT... ORDER BY..) UNION (SELECT .. ORDER BY...)does work.

简短的回答:(SELECT... ORDER BY..) UNION (SELECT .. ORDER BY...)确实有效。

See the documentationabout UNION:

请参阅有关以下内容的文档UNION

UNION Clause

The UNION clause has this general form:

select_statement UNION [ ALL | DISTINCT ] select_statement

select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, or FOR KEY SHARE clause. (ORDER BY and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)

联合条款

UNION 子句具有以下一般形式:

select_statement UNION [ ALL | DISTINCT ] select_statement

select_statement 是没有 ORDER BY、LIMIT、FOR NO KEY UPDATE、FOR UPDATE、FOR SHARE 或 FOR KEY SHARE 子句的任何 SELECT 语句。(ORDER BY 和 LIMIT 可以附加到子表达式,如果它被括在括号中。如果没有括号,这些子句将应用于 UNION 的结果,而不是它的右侧输入表达式。)