Fork me on GitHub

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

posted @ 2018-07-24 14:59  秋夜雨巷  阅读(34135)  评论(0编辑  收藏  举报