union的用法,以及如何對查詢到的資料排序

2021-08-21 16:30:12 字數 1392 閱讀 4602

如圖:是乙個好友驗證表,state表示好友狀態,1:通過驗證,0:未通過驗證,fromuser傳送請求者,touser接受請求者,現在要看看admin的好友,即fromuser或者touser的值為admin並且state的值的為1,並且按照時間倒序,資料不得重複!

正確結果是:測試者1,1234 兩個資料

結果是:

select distinct a.touser from (select touser,date from study_friend where state = 1 and fromuser = 'admin' union select fromuser,date from study_friend where state = 1 and  touser = 'admin') as a order by a.date desc

步驟1:將結果篩選出來,union本身有刪除重複資料的功能:

select touser from study_friend where state = 1 and fromuser = 'admin' union select fromuser from study_friend where state = 1 and  touser = 'admin'

步驟2:時間排序,union得到的資料會組成新的表,此表是乙個臨時表,對此表操作需要給它起乙個別名:

select  a.touser from (select touser,date from study_friend where state = 1 and fromuser = 'admin' union select fromuser,date from study_friend where state = 1 and  touser = 'admin') as a order by a.date desc

步驟3:整理,這是會發現資料是重複的,首先了解一下union的用法,兩個表查詢的字段個數必須一致,查詢得到的新表字段以第乙個語句的字段為準,本例中新表字段就是touser,date起別名也只能在第乙個表的字段下起,為什麼會有重複的呢?我們因為要給資料按時間排序,所以在兩個查詢中新增了date欄位,這是由union組成的新錶結果資料已經不是相同資料了因為date不同,那麼使用 distinct關鍵字篩選重複資料保留乙個。最終就是:

select distinct a.touser from (select touser,date from study_friend where state = 1 and fromuser = 'admin' union select fromuser,date from study_friend where state = 1 and  touser = 'admin') as a order by a.date desc

對union的遍歷運算

下面展示一些內聯 片。我們使用聯合查詢的時候,是為了將資料更好的組裝在一起,具體不多做介紹,可以看 內部的注釋 an highlighted block m operation m operatingreports info m operation where where field statist...

Liferay對union的處理

liferay中在finder裡面不支援unio的查詢,建議採用原生sql方式查詢 如下 獲取待辦流程 優化後的方法 只需要id字串集合 public static string getflow2 actionrequest request,long userid string flowids 獲取...

共用體 union 的用法

以前c語言學到union的時候,總是疑惑這傢伙該怎麼用,有什麼存在的價值,後來接觸到的東西多了,發現union這個定義還是有他的用武之地的。在定義union資料結構的時候,利用位差就可以很容易的讀出多位元組資料的高地位,甚至單個位元組的資料。例如 利用共用體型別的特點分別取出short型變數高位元組...