日常開發中,如果實用union all合併兩個已經排好序的結果集的時候,需求是第二個結果集資料排在第乙個結果集資料下面,單純的實用order by是無效的,因為order by的優先順序比union all低。
例如:select one.* from (select t1.* from table1 t1 where 1=1 and t1.day >3 order by t1.create_date desc) one
union all
select two.* from (select t2.* from table2 t2 where 1=1 and t1.day <=3 order by t2.create_date desc) two
此時查詢結果並不是安好two排序好之後 排在 one下面,如果要實現這樣的需求,可以使用乙個臨時字段作為排序字段,該字段的作用是使合併後的結果集有乙個統一的排序字段,合併前的結果集分別給預設值1和2,這樣在合併後的結果集可以排序了.
select all.* from (select one.* from (select t1.*,'1' as 'sortby' from table1 t1 where 1=1 and t1.day >3 order by t1.create_date desc) one
union all
select two.* from (select t2.* ,'2' as 'sortby' from table2 t2 where 1=1 and t.2day <=3 order by t2.create_date desc) two) all where 1=1 order by all.sortby asc
解決方案的巧妙之處就是,利用乙個自定義的字段實現兩個結果集的合併後排序。
合併兩個byte
byte sshead system.text.encoding.unicode.getbytes this is head byte sscontent system.text.encoding.unicode.getbytes this is content.sshead sscontent b...
合併兩個DataTable
方法1 sqlconnection myconnection new sqlconnection server localhost uid sa pwd database wjoa string sql1 select from resoursemanage t sqldataadapter ada...
合併兩個順序表
class program for int j 1 j 12 j 2 listresult merge left,right foreach int item in result console.writeline console.readline 由小到大的順序 public static lis...