SQL用了Union後的排序問題

2021-09-07 16:36:53 字數 2749 閱讀 4694

最近使用sql語句進行union查詢,驚奇的發現:sql沒問題,union查詢也沒問題,都可以得到想要的結果,可是在對結果進行排序的時候,卻出問題了。

1.union查詢沒問題

[sql]view plain

copy

select `id`,`username`,`mobile`,`time`,id as leader   

from `grouporder_leader`   

where `courseid` = 21 and `merchid` = 23 and `status` = 1   

union all   

select leadorderid,username,mobile,time,null   

from `grouporder_partner`  

where courseid=21 and status=1 and merchid=23  

結果如下

2.排序就出問題了

[sql]view plain

copy

select `id`,`username`,`mobile`,`time`,id as leader   

from `grouporder_leader`  

where `courseid` = 21 and `merchid` = 23 and `status` = 1   

order by time desc   

union all   

select leadorderid,username,mobile,time,null   

from `grouporder_partner`  

where courseid=21 and status=1 and merchid=23   

order by time desc  

執行這條sql語句之後就報錯。

3.建立臨時表

使用類似於建立臨時表的方法儲存查詢結果,然後對臨時表進行查詢排序。

[sql]view plain

copy

select id,username,mobile,time,leader   

from (select `id`,`username`,`mobile`,`time`,id as leader   

from `grouporder_leader` where `courseid` = 21 and `merchid` = 23 and `status` = 1   

union all   

select leadorderid,username,mobile,time,null   

from `grouporder_partner` where courseid=21 and status=1 and merchid=23  

)   

order by time desc  

4.起別名

不知道為什麼第3步中查詢依舊沒有,然後對union查詢的結果起個別名,然後再查詢排序就沒問題了。

[sql]view plain

copy

select a.id,a.username,a.mobile,a.time,a.leader   

from (select `id`,`username`,`mobile`,`time`,id as leader   

from `grouporder_leader` where `courseid` = 21 and `merchid` = 23 and `status` = 1   

union all   

select leadorderid,username,mobile,time,null   

from `grouporder_partner` where courseid=21 and status=1 and merchid=23  

) as a   

order by time desc  

結果就正確了

查出來就好說了,再進行去重或者其他操作,也沒問題.

[sql]view plain

copy

select distinct a.id,a.username,a.mobile,from_unixtime(a.time,'%y/%m/%d') as _time,a.leader   

from (select `id`,`username`,`mobile`,`time`,id as leader   

from `grouporder_leader` where `courseid` = 21 and `merchid` = 23 and `status` = 1   

union all   

select leadorderid,username,mobile,time,null   

from `grouporder_partner` where courseid=21 and status=1 and merchid=23  

) as a   

order by time desc

SQL用了Union後排序應該怎麼實現

最近使用sql語句進行union查詢,驚奇的發現 sql沒問題,union查詢也沒問題,都可以得到想要的結果,可是在對結果進行排序的時候,卻出問題了。日常開發中,如果實用union all合併兩個已經排好序的結果集的時候,需求是第二個結果集資料排在第乙個結果集資料下面,單純的實用order by是無...

sql 的聯合查詢union

乙個select查詢出來的結果其實也是一張表,而union就是把多個select查詢的結果 表 接成乙個結果。比如 select name,age,from comp user 執行後的結果為 周1,18,男 周2,20,女 select name 1,age 1,1 from dept user ...

SQL基礎 union的用法

一 區別1 取結果的交集 1 union 對兩個結果集進行並集操作,不包括重複行,相當於distinct,同時進行預設規則的排序 2 union all 對兩個結果集進行並集操作,包括重複行,即所有的結果全部顯示,不管是不是重複 二 區別2 獲取結果後的操作 1 union 會對獲取的結果進行排序操...