錯誤寫法,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
網上這種先排序再分組的,結果和上面一樣!!!並沒有取第一條!!!
參考: