union与union all与order by

来源:互联网 发布:淘宝模板大寸好吗 编辑:程序博客网 时间:2024/05/16 07:02

有时候我们会将两部分排序的结果联合起来显示,union会自动排序和去重,union all则不会

看以下sql语句:

select a,b,c from AA aa  where ...... order by aa.a desc

union all 

select a,b,c from  BB bb where ...... order by bb.a desc

会报错,原因是union all 最后一个select才能orderby 或者就嵌套一层再order by,如下:

select  * from  (select a,b,c from AA aa  where ...... order by aa.a desc)

union all

select  * from (select a,b,c from  BB bb where ...... order by bb.a desc)

0 0