1. 程式人生 > >group by查詢每組時間最新的一條記錄

group by查詢每組時間最新的一條記錄

詳細 describe 技術 .html location 取數 時間 index net

錯誤寫法,having time = max(time)在分組之後執行,查詢出來只有一條滿足條件的數據。having過濾的是組,在order by之後執行

        select id,userId,userFlag,lontitude,latitude,time,addr,locationdescribe
        from user_position
        group by userId
        having time = max(time)
        and userId in (select id from users where group_code=
(select group_code from users where id = #{userId})) ORDER BY time desc

數據格式

技術分享圖片

詳細步驟

1.查詢出分組的所有按時間降序的記錄id並拼接

--查詢出分組的所有按時間降序的記錄id並拼接
select group_concat(id order by `time` desc) from user_position group by userId

結果

技術分享圖片

2.查詢每個分組中時間最新的那條記錄的id

--查詢每個分組中時間最新的那條記錄的id
select SUBSTRING_INDEX(group_concat(id order
by `time` desc),,,1) from user_position group by userId

結果

技術分享圖片

3.所有成員最新一條記錄

select * from user_position as t 
where t.id in 
(
select SUBSTRING_INDEX(group_concat(id order by `time` desc),,,1) from user_position 
 group by userId
) 

4.根據id所在組查詢組成員最新數據

select * from user_position as
t where t.id in ( select SUBSTRING_INDEX(group_concat(id order by `time` desc),,,1) from user_position where userId in (select id from users where group_code=(select group_code from users where id = qyid1)) group by userId )

結果

技術分享圖片

巨坑

分組不是取數據的第一條!!!

select * 
from user_position as u 

查詢結果

技術分享圖片

select * 
from user_position as u 
group by u.userId 

分組後,確實取的第一條

技術分享圖片

但是!!!

select * 
from (
select * from user_position order by userId,time desc
) as u 
group by u.userId 

網上這種先排序再分組的,結果和上面一樣!!!並沒有取第一條!!!

技術分享圖片

參考:

https://www.cnblogs.com/Alight/p/3425357.html

https://www.jb51.net/article/23969.htm

group by查詢每組時間最新的一條記錄