• 实验环境基于Centos7.6

索引的基本管理:

1.索引建立前

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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: 辅助索引(单列,联和,前缀)

2.单列普通辅助索引

1
2
3
4
5
6
7
8
9
10
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;
注意:
以上操作不代表生产操作,我们不建议在一个列上建多个索引
同一个表中,索引名不能同名。
### 7.1.2 删除索引:
db01 [world]>alter table city drop index idx_name1;
表名 索引名

3.覆盖索引(联合索引)

1
Master [world]>alter table city add index idx_co_po(countrycode,population);

4.前缀索引

1
2
db01 [world]>alter table city add index idx_di(district(5));
注意:数字列不能用作前缀索引。

5.唯一索引

1
2
3
4
5
6
7
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';