如何在可能为空值的字段上创建唯一索引(Oracle 11g)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13042997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 01:11:29  来源:igfitidea点击:

How to create unique index on fields with possible null values (Oracle 11g)?

sqldatabaseoracleindexing

提问by Eric

Here is the sample table with 3 columns (ID, UNIQUE_VALUE, UNIQUE_GROUP_ID)

这是具有 3 列(ID、UNIQUE_VALUE、UNIQUE_GROUP_ID)的示例表

I want below records can be allowed:

我希望可以允许以下记录:

(1, NULL, NULL)
(2, NULL, NULL)

or

或者

(3, NULL, 7)
(4, 123, 7)

or (Note: this condition is not allowed in unique indexnor unique constraint)

或(注意:这种情况在unique index也不允许unique constraint

(5, NULL, 7)
(6, NULL, 7)

and these can't be allowed:

这些是不允许的:

(7, 123, 7)
(8, 123, 7)

I created a unique index on last 2 columns, but only the first 2 examples can be allowed.

我在最后 2 列上创建了一个唯一索引,但只能允许前 2 个示例。

Is it possible to let db check the uniqueness of these 2 columns only when both are not null?

仅当两者都不为空时,是否可以让 db 检查这 2 列的唯一性?

回答by Jeffrey Kemp

You want to only enforce uniqueness on the rows where both UNIQUE_VALUEand UNIQUE_GROUP_IDare not null. To do this, you can use a unique function-based index:

您只想在UNIQUE_VALUEUNIQUE_GROUP_ID都不为空的行上强制执行唯一性。为此,您可以使用唯一的基于函数的索引:

CREATE UNIQUE INDEX func_based_index ON the_table
  (CASE WHEN unique_value IS NOT NULL
         AND unique_group_id IS NOT NULL
        THEN UNIQUE_VALUE || ',' || UNIQUE_GROUP_ID
   END);

回答by planben

you can use the nvl function to avoid nulls and place a different value instead ,

您可以使用 nvl 函数来避免空值并改为放置不同的值,

create unique index func_idx on TEST_TABLE (nvl(UNIQUE_VALUE,1), UNIQUE_GROUP_ID);

the disadvantage is that your index will be larger and if you would like to search for null values you will have to use the nvl function in order to avoid table_access_full.

缺点是您的索引会更大,如果您想搜索空值,您将不得不使用 nvl 函数以避免 table_access_full。

also all of the null values will be located under one branch in the index , so make sure your histograms are updated.

此外,所有空值都将位于索引中的一个分支下,因此请确保您的直方图已更新。

I Hope this will help you :)

我希望这能帮到您 :)