索引:索引就像书的目录一样,如果在字段上建立了索引,那么以索引列为查询条件时,就可以加快查询速度。
主键索引
最快的索引,每个表只能有一个主键列,但是可以有多个普通索引。主键列要求所有的内容必须唯一,而普通索引列可以不唯一。
创建一个主键索引:
方法1:建立表的时候添加
MariaDB [suoyin]> create table student(
-> id int(4) not null AUTO_INCREMENT, ##AUTO_INCREMENT表示当为null时,id自动递加
-> name char(20) not null,
-> age tinyint(2) NOT NULL default '0',
-> dept varchar(16) default NULL,
-> primary key(id), ## 代表设定id列为主键列
-> KEY index_name(name) ##代表name字段普通索引
-> );
Query OK, 0 rows affected (0.01 sec)
删除普通索引:
MariaDB [suoyin]> alter table student drop index index_name; ##将name列的普通索引删掉
Query OK, 0 rows affected (0.14 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [suoyin]> drop index index_detp on student;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
方法2:建立表后添加主键索引(不推荐)
MariaDB [suoyin]> alter table student change id id int primary key auto_increment; ##表创建后,将id列转换为主键列
普通索引
1.唯一索引:因为主键只能存在一个,所以当主键设置后,另外的也可以被设为主键的索引,称为唯一索引
创建一个唯一索引:
MariaDB [suoyin]> create unique index uni_ind_name on student(name);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
通过"desc 表名 "查看
2.普通索引
创建一个普通索引:
MariaDB [suoyin]> alter table student add index index_detp(dept);
Query OK, 0 rows affected (0.15 sec)
Records: 0 Duplicates: 0 Warnings: 0
对字符串的前n列创建索引:
MariaDB [suoyin]> create index index_name on student(name(8));
Query OK, 0 rows affected (0.55 sec)
Records: 0 Duplicates: 0 Warnings: 0
查看表的索引:
MariaDB [suoyin]> show index from student\G
*************************** 1. row ***************************
Table: student
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: id
Collation: A
Cardinality: 2
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
*************************** 2. row ***************************
Table: student
Non_unique: 1
Key_name: index_detp
Seq_in_index: 1
Column_name: dept
Collation: A
Cardinality: 2
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
*************************** 3. row ***************************
Table: student
Non_unique: 1
Key_name: index_name
Seq_in_index: 1
Column_name: name
Collation: A
Cardinality: 2
Sub_part: 8
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
为表的多个列创建联合索引:(允许单个列上有它自己的索引)
MariaDB [suoyin]> create index ind_name_dept on student (name,dept);
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
联合索引的前缀生效特性:index(a,b,c)仅a,ab,abc三个查询条件可以走索引。