经常我们需要依据某列值来分组,查询最新数据,以下是方法一:
select *
from t
join (select max(t2.lastupdate) as m
from t t2
group by t2.computername) a on t.lastupdate=a.m
方法一在数据量小的时候没啥毛病,但是数据量到达百万级就是噩梦,原因就是临时表,大表连接。
以下是优化过的方法二,关联子查询:
select t.*
from t
where t.lastupdate = (select max(t2.lastupdate)
from t t2
where t2.computername = t.computername
);