UNION/UNION ALL和order by 連接使用

一.合併後排序

1.UNION/UNION ALL排序時,無論有多少個被union/union all的部分,只有最後一個union/union all部分才能擁有一個order by子句

2.UNION/UNION ALL的order by子句只能通過列號或別名來標示你要排序的字段

例: select t1.account_id account_id,t1.account_name account_name from t1

        union/union all

        select t2.account_id account_id,t2.account_name account_name from t2

        union/union all

        select t3.account_id account_id,t3.account_name account_name from t3

        order by 1/account_id;

注:"/"是或的意思,不代表是語法或具有含義。

二.排序後合併

1.多個結果集在被union/union all連接後仍然保持原有的排序,需要把結果集放在子查詢中

例: select * from

(select t1.account_id account_id,t1.account_name account_name from t1 order by t1.account_id)

        union/union all

select * from

        (select t2.account_id account_id,t2.account_name account_name from t2 order by t2.account_id)

        union/union all

select * from

        (select t3.account_id account_id,t3.account_name account_name from t3 order by t3.account_id)

        ;

注:"/"是或的意思,不代表是語法或具有含義。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章