当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL如何在已有的表上创建索引?

MySQL如何在已有的表上创建索引?

2018年12月21日  | 移动技术网IT编程  | 我要评论

1. 使用 alter table 语句创建索引

语法如下:

alter table table_name add [unique | fulltext | spatial ] [ index | key ]

[ index_name] ( col_name [length],…) [asc | desc]

index_name:索引名称,该参数作用是给用户创建的索引赋予新的名称。

table name:表名,即指定创建索引的表名称。

unique | fulltext | spatial 为可选参数,用于指定索引类型,分别表示唯一索引、全文索引、空间索引。

col_name:指定索引对应的字段名称。该字段必须已经预存在用户想要操作的数据表中,如果该数据表中不存在用户指定的字段,则会提示异常。

length:为可选参数,用于指定索引长度。

asc 和 desc 参数用于指定数据表的排序顺序。

【例】 在 score 表的 id 字段上建立,名为 id 的普通索引。sql语句如下:

mysql> alter  table  score  add index id (id(4));
query ok, 0 rows affected (0.41 sec)

使用 show index 语句查看表中的索引:

mysql> show  index  from  score  \g
*************************** 1. row ***************************
        table: score
   non_unique: 0
     key_name: primary
 seq_in_index: 1
  column_name: id
    collation: a
  cardinality: 0
     sub_part: null
       packed: null
         null:
   index_type: btree
      comment:
index_comment:
*************************** 2. row ***************************
        table: score
   non_unique: 1
     key_name: id
 seq_in_index: 1
  column_name: id
    collation: a
  cardinality: 0
     sub_part: null
       packed: null
         null:
   index_type: btree
      comment:
index_comment:
2 rows in set (0.00 sec)

主要参数含义:

1. table:表示创建索引的表。

2.non_unique:表示索引非唯一,1代表非唯 一索引, 0代表唯一索引。

3.key_name:表示索引的名称。

4.seq_in_index:表示该字段在索引中的位置,单列索引该值为1,组合案引为每个字段在索引定义中的顺序。

5.column_name:表示定义索引的列字段。

6.sub_part:表示索引的长度。

7.null:表示该字段是否能为空值。

8.index_type:表示索引类型。

2. 使用 create index 创建索引

语法如下:

cerate[unique | fulltext | spatial ] index index_name

on table_name( col_name [length] , … ) [asc | desc]

【例】在 address 表中 id 字段上建立名为 id 的唯一索引。

mysql> show create  table  address;
+---------+-------------------------------------------+
| table   | create table                                                                                                |
+---------+-------------------------------------------+
| address | create table `address` (
  `id` int(11) not null auto_increment,
  `name` varchar(50) default null,
  `address` varchar(200) default null,
  primary key (`id`)
) engine=innodb default charset=utf8 |

建立索引的sql语句:

mysql> create  unique  index  id
    -> on   address  (id);
query ok, 0 rows affected (0.33 sec)

查看创建结果:

mysql> show create  table  address ;
+---------+-----------------------------
| table   | create table                        |
+---------+--------------------------------------+
| address | create table `address` (
  `id` int(11) not null auto_increment,
  `name` varchar(50) default null,
  `address` varchar(200) default null,
  primary key (`id`),
  unique key `id` (`id`)
) engine=innodb default charset=utf8 |

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网