数据库对象索引是一种有效组合数据的方式,通过索引对象,可以快速查询到数据对象表中的特定记录,是一种提高性能的常用方式。
索引是创建子啊数据库表对象上,由表中的一个字段或多个字段生成的键组成,这些键存储在数据结构(B树或者哈希表中),从而快速查找与键值相关的字段。
创建和查看普通索引
创建表时创建普通索引
create table table_name(
属性名1 数据类型,
属性名2 数据类型,
......
index/key 索引名(属性名1 asc|desc,属性名2 asc|desc,...)
);
index或者key参数是用来指定字段为索引,asc代表索引为升序排序,desc代表为降序排序。默认为升序排序。
举个栗子:
create table t_dept(
deptno int,
dname varchar(20),
loc varchar(40),
index index_deptno(deptno)
);
在已经存在的表上创建普通索引
create index 索引名
on 表名(属性名 asc|desc);
on用来指定所要创建索引的表名称。
举个栗子:
create index index_deptno
on t_dept(deptno);
注:这里需要先创建t_dept;
通过alter table 创建普通索引
alter table table_name
add index|key 索引名(属性名 asc|desc);
举例:
alter table t_dept
add index index_deptno(deptno);
创建唯一索引
唯一索引,即是在创建索引时,限制索引的值必须是唯一的。
创建表时创建唯一索引
create table table_name(
属性名 数据类型,
属性名 数据类型,
......
属性名 数据类型,
unique index|key 索引名(属性名 asc|desc)
);
与创建普通索引相同,只需要加上unique。
在已经存在的表上创建唯一索引
create unique index 索引名
on 表名(属性名 asc|desc);
通过SQL语句alter table创建唯一索引
alter table table_name
add unique index|key 索引名(属性名 asc|desc);
创建和查看全文索引
全文索引主要关联在数据类型为char,varchar和text的字段上。
创建表时创建全文索引
create table table_name (
属性名 数据类型,
......
fulltext index|key 索引名(属性名 asc|desc)
);
在已经存在的表上创建全文索引
create fulltext index 索引名
on 表名(属性名 asc|desc);
通过SQL语句alter table创建全文索引
alter table table_name
add fulltext index|key 索引名(属性名 asc|desc);
创建多列索引
创建表时创建多列索引
create table table_name(
属性名1 数据类型,
属性名2 数据类型,
......
index|key 索引名(属性名1 asc|desc,属性名2 asc|desc)
);
asc|desc可以省略,默认为增序排序。
在已经存在的表上创建多列索引
create index 索引名
on 表名(属性名 asc|desc,属性名 asc|desc);
通过SQL语句alter table创建多列索引
alter table table_name
add index|key 索引名(属性名 asc|desc,属性名 asc|desc);
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!