部门id(b_code) | 最近登录时间(update) | 用户id(u_code) |
4 | 1617018911 | 1 |
3 | 1617038914 | 2 |
2 | 1617028915 | 3 |
2 | 1617048414 | 4 |
4 | 1617058917 | 5 |
1 | 1617078918 | 6 |
2 | 1617018921 | 7 |
表i_user,其中用户id主键
情况一:按照部门分组,查询出部门中用户id最大的一列
select * from i_user where u_code in(select max(u_code) from i_user GROUP BY b_code) ORDER BY b_code;
结果:
情况二:查询每个部门最近的登陆(刷新时间最大)用户
由于更新时间存在重复值,所以上面方法就不可行了。我们这里要用到mysql两个好玩的函数,GROUP_CONCAT和SUBSTRING_INDEX
select * from i_user where u_code in (select SUBSTRING_INDEX(GROUP_CONCAT(u_code ORDER BY `update` desc), ',', 1 ) from i_user GROUP BY b_code) ORDER BY b_code;
结果:
完毕!
扩展:
上诉方法属于我们很常考虑的mysql查询方式,其实还有一种相对来说不走寻常路的方法,我们可以使用自定义变量的方式来处理。
SET @tmpBuCode = "";
SET @rank = 1;
SELECT b_code,`update`,u_code
FROM
(
select b_code,`update`,u_code,
IF(@tmpBuCode = b_code, @rank:=@rank + 1, @rank:=1) as new_rank,
@tmpBuCode := b_code AS tmpBuCode
from (SELECT * FROM i_user ORDER BY b_code, `update` DESC) tn_a
) tb where new_rank <= 1;
这种方式就不需要考虑是否是唯一健值的因素了,而且他还能很好的完成分组查询出前n条记录的功能!