使用索引的误区之四:空值对索引的影响

来源:互联网 发布:北京ps软件培训 编辑:程序博客网 时间:2024/05/01 01:21
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
使用索引误区之四:空值对索引影响
我们首先做一些测试数据:

SQL>createtablet(xint,yint);

 

Tablecreated

 

请注意,这里我对表t做了一个唯一(联合)索引

SQL>createuniqueindext_idxont(x,y);

 

Indexcreated

 

SQL>insertintotvalues(1,1);

 

1rowinserted

 

SQL>insertintotvalues(1,NULL);

 

1rowinserted

 

SQL>insertintotvalues(NULL,1);

 

1rowinserted

 

SQL>insertintotvalues(NULL,NULL);

 

1rowinserted

 

SQL>commit;

 

Commitcomplete

 

下面我们分析一下索引

SQL>analyzeindext_idxvalidatestructure;

 

Indexanalyzed

 

SQL>selectname,lf_rowsfromindex_stats;

 

NAME                             LF_ROWS

----------------------------------------

T_IDX                                  3

 

SQL>

然后,我们就可以看到,当前的索引中仅仅保存了3行数据。

请注意,上面我们插入并提交了四行数据。

所以,这里就有一个结论:

索引不保存全部为空的行。

 

 

我们继续插入数据,现在再插入几行全部为空的行:

SQL>insertintotvalues(NULL,NULL);

 

1rowinserted

 

SQL>insertintotvalues(NULL,NULL);

 

1rowinserted

我们看到这样的插入,居然没有违反前面我们设定的唯一约束(uniqueont(x,y)),

所以,这里我们又得出一个结论:

Oracle认为NULL<>NULL,进而(NULL,NULL)<>(NULL,NULL)

换句话说,Oracle认为空值(NULL)不等于任何值,包括空值也不等于空值。

 

我们看到下面的插入会违反唯一约束(DEMO.T_IDX),这个很好理解了,因为它不是全部为空的值,即它不是(NULL,NULL),只有全部为空的行才被认为是不同的行:

SQL>insertintotvalues(1,null);

 

insertintotvalues(1,null)

 

ORA-00001:违反唯一约束条件(DEMO.T_IDX)

 

SQL>insertintotvalues(null,1);

 

insertintotvalues(null,1)

 

ORA-00001:违反唯一约束条件(DEMO.T_IDX)

 

SQL>

 

请看下面的例子:

SQL>selectx,y,count(*)fromtgroupbyx,y;

 

   X       Y  COUNT(*)

-----------------------

                       3

            1         1

   1                  1

   1       1         1

Executedin0.03seconds

 

SQL>selectx,y,count(*)fromtwherexisnullandyisnullgroupbyx,y;

 

  X      Y  COUNT(*)

---------------------

                     3共4页  第1页   
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击