暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

什么是索引,为什么用索引,什么时候用,什么时候不用,怎么用

东面而视 2018-07-24
176

什么是索引?

索引就是将表中某几个字段提取出来,开辟新的存储空间并进行排序,并且把所有值和rowid存储其中,并用一个指针指向表中原来对应行的记录。

 

为什么用索引:

  1. 快速查找数据库表中某条数据;

  2. 减少I/O操作。

什么时候用:

  1. 作为where后查询条件的字段适合建立索引。

什么时候不用:

  1. 重复字段较多;

  2. 不作为where后查询条件的字段;

  3. 表中记录较少。

怎么用索引:

创建索引:

  1. CREATE [UNIQUE] | [BITMAP] INDEX index_name  --unique表示唯一索引

  2. ON table_name([column1 [ASC|DESC],column2    --bitmap,创建位图索引

  3. [ASC|DESC],…] | [express])

  4. [TABLESPACE tablespace_name]

  5. [PCTFREE n1]                                 --指定索引在数据块中空闲空间

  6. [STORAGE (INITIAL n2)]

  7. [NOLOGGING]                                  --表示创建和重建索引时允许对表做DML操作,默认情况下不应该使用

  8. [NOLINE]

  9. [NOSORT];                                    --表示创建索引时不进行排序,默认不适用,如果数据已经是按照该索引顺序排列的可以使用


例如,

创建商品表:

  1. -- Create table

  2. create table TB_GOODS

  3. (

  4. goods_id    VARCHAR2(64) not null,

  5. goods_name  VARCHAR2(256) not null,

  6. goods_price VARCHAR2(64) not null,

  7. status      VARCHAR2(1) not null

  8. );


创建索引:

  1. --这里unique可以省略,若省略则索引为非唯一索引

  2. create index UI_tb_goods on tb_goods(goods_name);

  3. --若使用unique则为唯一索引

  4. create unique index un_tb_goods on tb_goods(goods_name);

  5. --括号中添加两列则为组合索引

  6. create unique index un2_tb_goods on tb_goods(goods_name,status);

  7. --括号中添加三列,其顺序没有关系,效果是一样的

  8. create unique index un3_tb_goods on tb_goods(goods_name,goods_price,status);


唯一索引的另一个作用,控制列不能有相同值

 

查询索引:

  1. select * from user_indexes where table_name='表名';

  2. select * from user_ind_columns  where index_name='索引名';



文章转载自东面而视,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论