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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值