【问题标题】:Optimized query to get the most recent records for each person in a log table优化查询以获取日志表中每个人的最新记录
【发布时间】:2021-07-02 20:52:04
【问题描述】:
有没有更好的方法来设置这个查询?
select *
from peopleLog
where index in (select max(index) index from peopleLog group by personID)
我有一个日志表,每次更新一个人的记录时都会插入该表。记录被添加,而不是被替换。这意味着该表包含每个人的多条记录。我想从这张表中提取每个人最讨厌的记录。该表有大约 30 个字段,所以我认为分组不是最好的选择,但我可能错了。
- 索引字段是此 SQL Server 表中的标识字段,并设置为自动递增。
- personID 是个人的识别号码,是个人唯一的。
【问题讨论】:
标签:
sql
sql-server
query-optimization
【解决方案1】:
你可以使用窗口函数来代替:
select * from (
select * , row_number() over (partition by personID order by index desc) rn
from peopleLog
) t where t.rn = 1
personId 和“index”列的索引也会有所帮助)
【解决方案2】:
通常相关子查询具有最佳性能:
select pl.*
from peopleLog pl
where pl.index = (select max(pl2.index)
from peopleLog pl2
where pl2.personID = pl.personID
);
特别是,这可以利用peopleLog(personID, index) 上的索引。