【发布时间】:2020-06-23 00:13:31
【问题描述】:
第一篇文章在这里。我需要从表中提取最新值,但对于给定日期,此特定表中有许多条目。我对下面的两个选项做了类似的事情。
选项 1.. 将主表加入子查询表:
select t1.key, t1.date, t2.value
from table1 t1
join
(select key,
date,
max(updated_at) as last_update
from table2
group by 1,2) t2
on t1.key = t2.key
and t1.date = t2.date
and t1.updated_at = t2.last_update
order by 1,2;
选项 2.. 连接中的子查询和带有限制的降序“排序依据”:
select t1.key, t1.date, t2.value
from table1 t1
join table2 t2
on t1.key = t2.key
and t1.date = t2.date
and t2.updated_at = (
select updated_at
from table2
where key = t2.key
and date = t2.date
order by updated_at desc
limit 1)
order by 1,2;
选项 2 有点不典型,并且需要在子查询中对整个表进行排序,所以我怀疑这是最佳做法,但它可以工作并且允许子查询存在于 Join 中,所以我之前使用过它。
选项 1、选项 2 或某些选项 3 是解决此问题的最有效方法吗?什么是最佳做法?浏览 Stack 一段时间后很高兴加入,谢谢大家。
【问题讨论】:
标签: sql database postgresql performance join