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


錯誤寫法,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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM