• 基于Centos7.6

1.索引建立前

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
查看索引信息
db01 [world]>desc city;
+-------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| Name | char(35) | NO | | | |
| CountryCode | char(3) | NO | MUL | | |
| District | char(20) | NO | | | |
| Population | int(11) | NO | | 0 | |
+-------------+----------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

Field :列名字
key :有没有索引,索引类型
PRI: 主键索引
UNI: 唯一索引
MUL: 辅助索引(单列,联和,前缀)
更详细的索引信息使用show index from city;查看

2.创建索引

1
2
3
4
5
6
7
8
9
10
1>创建单列辅助索引
db01 [world]>alter table city add index idx_name(name);
表 索引名(列名)
db01 [world]>create index idx_name1 on city(name);
db01 [world]>show index from city;

注意:
以上操作不代表生产操作,我们不建议在一个列上建多个索引
同一个表中,索引名不能同名。
创建索引会锁表,尽量在业务不繁忙期间操作。
1
2
2>创建多列联合索引
Master [world]>alter table city add index idx_co_po(countrycode,population);
1
2
3
4
5
6
7
8
9
10
3>唯一索引
db01 [world]>alter table city add unique index idx_uni1(name);
ERROR 1062 (23000): Duplicate entry 'San Jose' for key 'idx_uni1'
有重复,此列无法建立唯一索引

统计city表中,以省的名字为分组,统计组的个数
select district,count(id) from city group by district;
需求: 找到world下,city表中 name列有重复值的行,最后删掉重复的行
db01 [world]>select name,count(id) as cid from city group by name having cid>1 order by cid desc;
db01 [world]>select * from city where name='suzhou';
1
2
3
4
4>前缀索引
只有字符串列可以做前缀索引
db01 [world]>alter table city add index idx_di(district(5)); #前5个字符做索引
注意:数字列不能用作前缀索引。

3.删除索引

1
2
db01 [world]>show index from city;
db01 [world]>alter table city drop index idx_name;