SQL分組排序後取每組最新一條資料的另一種思路

2022-02-26 18:09:19 字數 1304 閱讀 6396

在hibernate框架和mysql、oracle兩種資料庫相容的專案中實現查詢每個id最新更新的一條資料。

之前工作中一直用的mybatis+oracle資料庫這種,一般寫這類分組排序取每組最新一條資料的sql都是使用row_number() over()函式來實現

例如:select t1.* from (

select t.*,

row_number() over(partition t.id order by t.update_time desc) as rn

from table_name t

) t1 where t1.rn = 1;

但是新公司專案是相容mysql和oracle兩種資料庫切換的,那麼row_number() over()在使用mysql的情況下會出現錯誤,所以我在網上查詢了一下mysql實現分組排序取最新資料的例子

有兩種寫法,如下:

第一種select t1.*

from table_name t1,

(select t.id, max(t.update_time) as utime from table_name t group by t.id) t2

where 1=1

and t1.id = t2.id

and t1.update_time = t2.utime;

第二種(這裡limit是為了固定子查詢中的排序,如果沒有這個limit,外層使用虛擬表t1進行group by的時候就不會根據之前update_time排好的倒序進行分組了。limit具體的數字可以根據要查詢資料的總數來決定。)

select t1.* from (

select * from table_name t order by t.update_time desc limit 1000

) t1 group by t1.id;

這裡又遇到了乙個問題,雖然第一種方式使用mysql和oracle都可以查詢,但是hibernate是不支援from (子查詢) ... 這種結構的sql的,因為hibernate的核心是物件導向而非面向資料庫,網上搜到是這種解決方案

為了乙個子查詢再新建乙個實體類...雖然覺得這樣有點麻煩但是我還是搜尋了一下整個專案看有沒有類似的做法,結果乙個都沒有找到!

這時候我請教了一下部門的老人想看看他們做這類查詢是如何處理的,大佬給出的方案是換一種sql寫法

如下:select * from table_name t1 where t1.update_time= (select max(t.update_time) from table_name t where t.id= t1.id);

至此問題解決...

mysql 分組取最新一條

mysql 分組取最新一條 select from select from usr warn info handle order by handle time desc limit 10 t group by warn info idusr warn info handle 表名 handle ti...

Mysql 分組取最新一條

我有如下這張表的資料,需要根據mobile 號碼分組,每條 取最新的資料 方案1 select from select from model online forecastscore phone0001 order by id desc as cn group by cn.mobile 方案2 最佳...

sql 取最新一條記錄

1.選出某個條件最新的一條記錄 選出最新狀態下的每乙個單號對應的子單資料 select distinct a.receiving code,a.product barcode,a.rd putaway qty from odoo ykd oversea shipping information a ...