union中的order by的应用

来源:互联网 发布:英伟达游戏优化软件 编辑:程序博客网 时间:2024/06/05 12:03

只能在union的最后一个子句后使用order by,并且此时order by的作用对象是union后的整个结果集。

如果子查询的列名不相同,如:

select  A,Bfrom tableAunionselect C,Dfrom tableB

此时如果在第二个子查询后加上"order by C"就会报错,这种情况只能使用"order by A"。因为union后结果集的列名取的是第一个子查询的列名。


为了避免出现上面的错误可以采用下面的方法

1.统一所有子查询的列名

select  A,Bfrom tableAunionselect C as A,D as Bfrom tableBorder by A
2.使用列序号代替列名

select  A,Bfrom tableAunionselect C,Dfrom tableBorder by 1


0 0