当前位置: 移动技术网 > IT编程>数据库>Mysql > Mysql-索引

Mysql-索引

2020年03月18日  | 移动技术网IT编程  | 我要评论

先创建表

mysql> create table test(
    -> id int,
    -> username varchar(16),
    -> city varchar(16),
    -> age int
    -> );

1.普通索引

是最基本的索引,它没有任何的限制。有以下几种创建方式

(1)直接创建索引:

create index index_name on table(column(length))
 实例:
create index test_username on test (username(10)); -->单列索引

indexname为索引名,mytable表名,username和city为列名,10为前缀长度,即索引在该列从最左字符开始存储的信息长度,单位字节

如果是char,varchar类型,前缀长度可以小于字段实际长度;如果是blob和text类型,必须指定 前缀长度,下同。

(2)修改表结构的方式添加索引

alter table table_name add index index_name on (column(length))
alter table test add index test_username(username(10));

此处 indexname 索引名可不写,系统自动赋名 username ,username_2 ,username_3,...

(3)创建表的时候同时创建索引

mysql> create table test( -> id int, -> username varchar(16), -> city varchar(16), -> age int, -> index test_username (username(10)) -> );

2.唯一索引

与前面的普通索引类似,不同的就是:索引列的值必须唯一,但允许有空值。如果是组合索引,则列值的组合必须唯一。它有以下几种创建方式:
(1)创建唯一索引

create unique index indexname on table(column(length))
  实例:

create unique index test_city on test(city(10));

(2)修改表结构

alter table table_name add unique indexname on (column(length))
(3)创建表的时候直接指定

mysql> create table test( -> id int, -> username varchar(16), -> city varchar(16), -> age int, -> unique test_username (username(10)) -> );

3.主键索引

是一种特殊的唯一索引,一个表只能有一个主键,不允许有空值。一般是在建表的时候同时创建主键索引:

主键索引无需命名,一个表只能有一个主键。主键索引同时可是唯一索引或者全文索引,但唯一索引或全文索引不能共存在同一索引

(1)修改表结构创建

alter table test add primary key (id);
(2)创建表的时候直接指定

mysql> create table test(
-> id int,
-> username varchar(16),
-> city varchar(16),
-> age int,
-> primary key(id)
-> );
```

4.组合索引

指多个字段上创建的索引,只有在查询条件中使用了创建索引时的第一个字段,索引才会被使用。使用组合索引时遵循最左前缀集合

alter table test add index test_username_city (username,city);

5.全文索引

主要用来查找文本中的关键字,而不是直接与索引中的值相比较。fulltext索引跟其它索引大不相同,它更像是一个搜索引擎,而不是简单的where语句的参数匹配。fulltext索引配合match against操作使用,而不是一般的where语句加like。它可以在create table,alter table ,create index使用,不过目前只有char、varchar,text 列上可以创建全文索引。值得一提的是,在数据量较大时候,现将数据放入一个没有全局索引的表中,然后再用create index创建fulltext索引,要比先为一张表建立fulltext然后再将数据写入的速度快很多。

(1)直接创建

create fulltext index full_username on test (username);

(2)修改表结构添加全文索引

alter table test add fulltext index full_city (city);

(3)创建表的时候直接指定

mysql> create table test(
    -> id int,
    -> username varchar(16),
    -> city varchar(16),
    -> age int,
    -> fulltext indexname (username(10))
    -> );

6.查看索引

第一种:show create table test;
第二种:show index from test \g;

7.删除索引

drop index index_name on table;
alter table test drop primary key;  -->删除主键

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

相关文章:

验证码:
移动技术网