【问题标题】:How does sql optimization work internally?sql优化在内部是如何工作的?
【发布时间】:2010-01-22 05:37:29
【问题描述】:

我之前的问题:

Date of max id: sql/oracle optimization

在我之前的问题中,我正在寻找不同的方法来查找具有最高 ID 号的记录的日期。以下是一些提供的解决方案,以及由解释计划计算得出的“成本”。

select date from table where id in (
select max(id) from table)

成本为 8

select date from table where rownum < 2 order by id desc;

成本为 5

select date from (select date from table order by id desc) where rownum < 2;

也有成本 5

with ranked_table as (select rownum as rn, date from table order by id desc)
  select date from ranked_table where rn = 1;

成本为 906665

SELECT t1.date
FROM table t1
LEFT OUTER JOIN table t2
  ON t1.id < t2.id
WHERE t2.id IS NULL;

成本为 1438619

显然 id 上的索引正在发挥作用。但我想知道,在什么情况下,最后两个表现至少一样好,如果不是更好?我想了解这样做的好处。

这是在 Oracle 中完成的。所有品种都可以讨论,但请说出你的答案适用于什么。

【问题讨论】:

    标签: sql optimization


    【解决方案1】:

    如果您想要最便携的 SQL 以适用于各种其他品牌的 RDBMS(即并非所有品牌都支持 rownum),请使用解决方案 #1:

    select date from table where id in (select max(id) from table);
    

    如果您想要最有效的 Oracle 解决方案,请使用解决方案 #3:

    select date from (select date from table order by id desc) where rownum < 2;
    

    请注意,解决方案#2 并不总是给出正确的答案,因为它返回“前”两行之前它已按id 对它们进行排序。如果这恰好返回具有最高 id 值的行,那只是巧合。

    select date from table where rownum < 2 order by id desc;
    

    关于更复杂的查询 #4 和 #5 会产生如此高的成本,我同意我不建议将它们用于获取具有最高 id 的行这样简单的任务。但是了解如何使用子查询分解和自联接对于解决其他更复杂的查询类型很有用,因为简单的解决方案根本无法完成这项工作。

    示例:给定主题论坛 cmets 的层次结构,显示具有最直接回复的“最热门” cmets。

    【讨论】:

      【解决方案2】:

      几乎所有体面的数据库都引入了称为优化器提示的指令,这些指令不可移植,连接表有默认成本,您可以建议查询优化器使用嵌套循环连接或动态表哈希连接。您在oracle performance tuning guide 中找到了对 Oracle 的一个很好的解释

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-01
        • 2020-05-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多