SQL syntax error at or near 'union'

不想你离开。 提交于 2019-12-05 17:07:33

问题


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'

回答1:


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.




回答2:


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

See the documentation about 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.)



来源:https://stackoverflow.com/questions/24020078/sql-syntax-error-at-or-near-union

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!