UNION 查詢中的排序

2021-09-09 00:21:22 字數 1138 閱讀 6224

mssql 不允許在union查詢中使用 order by 因此,當我們需要這種功能的時候,就需要繞一些彎路.

比如有一張學生表student 和教師表 teacher , 我們要查詢所有的教師學生的姓名和年齡,教師排前面,學生排後面,分別按字母順序,則可能會想寫乙個這樣的sql語句: (注意,這個語句只是為了說明問題,這並不是乙個正確的語句)

select name,age from teacher order by name 

union 

select name,age from student order by name

實際上,mssql並不允許我們寫這樣的語句,因此將會報錯 union 附近有語法錯誤.

其實我們只需要繞開,讓order by 和union 不在同一層, 讓order 在子查詢內而 union 在外面(因為我們要先教師學生分開,然後再名字) 這樣得到了另外乙個sql語句:(注意,這依然不是乙個正確的語句)

select * from (select name,age from teacher order by name) a 

union 

select * from (select name,age from student order by name) b

這句sql語句依然無法通過,因為這又觸犯了mssql的另外一條語法規定,在子查詢中, 如果不存在top語句則order by子句無效. 但是我們需要的是全部結果,並不需要top的功能.  顯然, top 100% 是個解決的方法. 因為100%就是全部了.

最後,這條蹩腳的sql語句出爐了:

select * from (select top 100 percent name,age from teacher order by name) a 

union 

select * from (selecttop 100 percent name,age from student order by name) b

這就是最後的結果, 為了讓order by 和union同時發揮作用,繞了2個彎.

如果想union前面和後面的集合分開,使用union all,但要去除重複的記錄。

UNION 查詢結果排序

今天想統計幾個結果資料,於是用到了union關鍵字 select count 1 from xx a union select count 1 from xx b union select count 1 from xx c這樣查詢的結果會預設按公升序排列,也就是a表的結果可能排在最後。通過檢視文件...

mysql 中關於 union 查詢多表排序的問題

union 若是不使用表的命名空間直接排序的話只需要在語句後直接加order by就可以 select name,age,day from user1 union select name,age,day from user2 order by day這樣可以直接對兩個表綜合排序 但是如果使用命名空間...

複雜查詢中 union的使用

union可以將幾條sql命令合成一條,要求是這幾條命令生成的表,在字段個數 字段型別 字段長度 字段順序上都完全一樣。以下這種情況,一般都要使用它的 把幾個結構完全一樣的表的記錄都加在一起,最後生成的表,在結構上跟那幾個表也完全一樣,但記錄數就是那幾個表的記錄數的總和。舉個例子 我想統計一段時間內...