mysql sql 笔记-获取分组中某个字段的最大的行

获取分组中某个字段的最大的行:
+----+---------+------+--------+
| id | name    | age  | utype  |
+----+---------+------+--------+
|  1 | nick    |   18 | normal |
|  2 | rose    |   20 | normal |
|  3 | richard |   22 | admin  |
|  4 | sarah   |   18 | admin  |
|  5 | adney   |   25 | admin  |
|  6 | jack    |   25 | admin  |
+----+---------+------+--------+

按 utype 分组,获取每个用户类型中年龄 age 的最大的行;
1 .

select * from user where age in (select MAX(age) from user group by utype);

2 . 注:1

select * from user as b where not exists(select 1 from user where utype= b.utype and b.age<age); 

结果:

+----+-------+------+--------+
| id | name  | age  | utype  |
+----+-------+------+--------+
|  2 | rose  |   20 | normal |
|  5 | adney |   25 | admin  |
|  6 | jack  |   25 | admin  |
+----+-------+------+--------+

插入到另一个表中:

insert into usercopy select * from user where age in (select MAX(age) from user group by utype);

insert into usercopy select * from user as b where not exists(select 1 from user where utype= b.utype and b.age<age); 

插入到一个新表中:

create table usercopy select * from user where age in (select MAX(age) from user group by utype);

create table usercopy select * from user as b where not exists(select 1 from user where utype= b.utype and b.age<age); 

如果在上面筛选记录的基础上只取 id 最大的一行:

select * from user where id in (select MAX(id) from user where age in (select MAX(age) from user group by utype) group by utype);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值