【问题标题】:Oracle: Indexing a subset of rows of a tableOracle:索引表的行子集
【发布时间】:2011-12-01 03:00:52
【问题描述】:

我有一个表,其中包含活动和非活动条目,活动 = 1 表示活动,活动 = 0 表示不活动。

我在这个表上有各种索引,但我只需要为活动条目维护索引,因为应用程序只查询活动数据。需要保留非活动数据,因为它可以再次变为活动状态,但这通常仅通过批量更新完成,无论如何都不会使用索引。

我注意到索引非活动条目(越来越多的活动条目)需要相当多的空间。

Oracle (10g) 中有没有办法做这样的事情:

create index an_idx on tab (active, col1, col2, ... , coln) where active = 1?

上一次尝试:

active = 0 像这样时,我尝试使用基于函数的索引将第一列设置为空:

create index an_idx on tab (decode(active, 1, 1, null), col1, col2, ... , coln)

但在这种情况下,Oracle 似乎仍然为非活动列编制索引。

【问题讨论】:

标签: sql database oracle indexing


【解决方案1】:

按 ACTIVE 对表进行分区,创建本地索引,并使非活动分区的索引不可用。这将消除索引非活动数据所花费的时间。

create table tab(active number, col1 number, col2 number, col3 number)
    partition by list(active) 
    (partition tab_active values(1), partition tab_inactive values(0));

create index tab_index1 on tab(col1) local;

alter index tab_index1 modify partition tab_inactive unusable;

但是这种方法有一些潜在的缺点:

  • 并非所有类型的索引都无法使用。
  • 数据库中有不可用的对象是不正常的。人们可能会抱怨它或认为它是一个错误并重新构建它。
  • 某些操作(例如截断)会自动使索引再次可用。

在 Oracle 12c 中,您可以使用 partial indexes 完成此操作:

create table tab(active number, col1 number, col2 number, col3 number)
    partition by list(active) 
    (partition tab_active   values(1) indexing on,
     partition tab_inactive values(0) indexing off);

create index tab_index1 on tab(col1) local indexing partial;

【讨论】:

    【解决方案2】:

    您的基本想法是正确的,但您需要将解码应用于所有列。只有当所有被索引的表达式都是NULL时,该行才会被索引。

    create index an_idx on tab (
      decode(active, 1, col1, null),
      ...
      decode(active, 1, coln, null)
    )
    

    当然,如果您希望查询使用此索引,则必须在 WHERE 子句中使用相同的表达式。

    请注意,我认为您不想在索引中包含表达式 decode(active, 1, 1, null),因为它对于所有索引行都是常量。

    【讨论】:

    • 感谢您的解决方案。我担心我不得不做这样的乱七八糟的事情。认为可能有更清洁的东西。
    【解决方案3】:

    我认为这是不可能的。有几个选择

    1. 在 (active, col1...) 上建立索引,这样查询时间就不会受到影响 不活跃的元素也一样
    2. 为活动/非活动项目创建两个表,并通过在两个表之间移动内容来管理活动状态
    3. 创建第二个表,其中包含要索引的所有数据以及唯一标识符,然后加入该表以获取其余数据。

    【讨论】:

    • 如果节省空间是您的目标,那么选项 2 将是 IMO。
    猜你喜欢
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2013-04-24
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多