有两张表loginrecords(登录记录)和trusteddevices(信任设备),这两张表通过设备的Id关联,现在想查出每个信任设备最近的一条登录记录应该怎么写SQL语句呢?
分析一下,我们可以先选出某个信任设备的所有登陆记录,然后去除掉重复记录只保留LoginTime最大的那一条。事实上用not exists可以实现。语句如下:
select d.*,a.* from trusteddevices d left join loginrecords a on d.Id = a.deviceId where (not exists ( select b.* from loginrecords b where b.deviceId = a.deviceId and a.LoginTime < b.LoginTime));
但是not exists只适合数据量不大而且最好有索引的情况下,当数据越来越多的时候执行起来会比较费时间。
想办法优化一下SQL语句,去重我们会想到用distinct,但是distinct *是作用于所有列的,往往只用来返回不重复记录的条数,并不能帮我们筛选出想要的数据。
实际上可以用如下语句完成优化:
select d.*,r.* from trusteddevices d left join loginrecords r on r.deviceId = d.Id where r.Id = (select Id from loginrecords where DeviceId = d.Id order by LoginTime desc limit 1);