sql 分组取最值
create table mobilelog(
id int primary key auto_increment, /* 自增id */
mobile varchar(26), /* 手机号码 */
log varchar(55), /* 日志信息 */
createtime datetime /* 创建时间 */
);
获取每个手机号码最新的日志信息
先获取所有号码最新的id,此处需要同过id区分每条日志,因为createtime可能重复。
select max(id) from mobilelog group by mobile;
通过id获取日志信息:
select * from mobilelog where id in (select max(id) from mobilelog group by mobile);
获取部分号码的最新日志信息:
select * from mobilelog where id in
(select max(id) from mobilelog where mobile in ('15209864032','17209864032')
group by mobile);
select * from (
select mobile,log from mobilelog ORDER BY mobile,id desc
)t
GROUP BY t.mobile;