where 子句中的内部查询在 postgres 中花费时间

问题描述 投票:0回答:1

我试图从表中检索具有最大影响日期的行,但日期应该大于当前日期,因此我添加了内部查询,但添加内部查询后需要很长时间才能返回结果。

select
* 
from 
   mytable 
where 
   empno = '1234' 
and  
   effect_date = (select
        max(effect_date)
   from 
        mytable 
   where 
        empno = '1234' 
   and 
        effect_date <= current_date)

任何人都可以建议我如何优化它吗?

提前致谢。

postgresql pgadmin
1个回答
0
投票

您可以使用以下方法避免获取最大日期子查询:

select * 
  from mytable 
 where empno = '1234'
   and effect_date > current_date 
 order by effect_date desc
 limit 1;

但这涉及到排序。它可能不会更快,但除非你尝试,否则你无法知道。尽管如此,如果在

empno
effect_date
上建立索引,它仍然会受益。

© www.soinside.com 2019 - 2024. All rights reserved.