【问题标题】:Why to use Correlated Subqueries?为什么要使用相关子查询?
【发布时间】:2021-03-10 08:22:48
【问题描述】:

据我所知,可以使用多列子查询或连接来重写相关子查询。而且它们通常比相关子查询执行得更好。

那么在哪些可能的情况下,关联子查询可能是更好的选择还是唯一的选择? (我使用 Oracle 数据库)

【问题讨论】:

  • 方便EXISTS
  • 对于NOT EXISTS 更方便:-)

标签: sql oracle oracle11g sqlperformance sql-tuning


【解决方案1】:

Oracle 有一个很好的优化器,但关联子查询有时是表达查询的最有效方式。例如:

select t.*,
       (select count(*) from z where z.t_id = t.id)
from t;

使用z(t_id) 上的索引可以非常有效,因为它避免了外部聚合。

还有其他情况,它们既高效又直接转化为问题:获取z中不存在的所有ts。

select t.*
from t
where not exists (select 1 from z where z.id = t.id);

最后,相关子查询只是横向连接的一个示例。横向连接可能非常强大。例如,要获取上一行的所有列,您可以使用:

select t.*, t2.*
from t cross join lateral
     (select t2.*
      from t t2
      where t2.date < t.date
      order by t2.date desc
      fetch first 1 row only
     ) t2;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2020-11-15
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多