SQL需求
根据username和client分组,并查询出每组中最新一条数据中的字段
解析
数据库为MySQL 8.0.23
因为id自增,并且业务中没有对id进行修改的情况,所以最新一条即id最大数据
需求实现则是分组后查询出每组id最大的数据
方法一(之前)
select id, username, client, status
from t_user t
where id = (
select MAX(id)
from t_user
where t.username = username
AND t.client = client
);
根据where条件实现两个表的连接,根据id去逐个进行筛选
耗时
1s203ms
方法二
select id, username, client, status
from t_user t
where id in (
select max(id)
from t_user
group by username, client
)
首先分组,找到每组中最大的id,使用in来查找,相比方法二,就是减少了需要进行查找的数据
耗时
312ms
方法三
select id, username, client, status
from t_user t
join (
select MAX(id) id
from t_user
group by username, client
) t2 on t.id = t2.id
方法三是在方法二的基础上,将in替换为join
耗时
327ms