zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    [Git]08 如何自动补全命令
    [Git]06 如何提交空目录
    [Git]05 如何使用分支
    [Git]04 如何使用标签
    [Git]03 如何查看提交历史
    29、前端知识点--sessioncookie oken
    28、前端知识点--跨域问题
    26、前端知识点--利用webpack搭建脚手架一套完整流程
    25、前端知识点--webpack篇之面试考点
    24、前端知识点--数组的合并
  • 原文地址:https://www.cnblogs.com/aeolian/p/9359898.html
Copyright © 2011-2022 走看看