union all 与order by的连用

昨天工作过程中发现一个奇怪的地方:

代码段A:

1---select   *  from  table1  

2---order  by  no 

3---union  all

4---select   *  from  table2

运行代码段1,在第三步显示命令未正确结束。我自然很困惑,问了前辈才知道原来问题出在order  by上。

修改后的代码段A1:

1---select   *  from  table1  

2---union  all

3---select   *  from  table2

4---order  by  no 

修改后的代码A1可正常运行。

我在网络上找了很多说法:

说法1:order  by的优先级低于union all,代码段A中会先运行union all,再运行order by。(但是这个为什么会对运行有影响呢?)

说法2:order by是在本地运行的。(这个也没想明白影响的原因。)

决定再问一下前辈。

看来对于数据库我还有很多不知道的地方。要多多学习,多多进步。

原文地址:https://www.cnblogs.com/cyfighting/p/6231705.html