Linux数据库学习 索引基本管理如何操作 老男孩培训

    /    2019-05-30

更多内容请关注微信公众号:老男孩Linux


7. 索引的基本管理

7.1 索引建立前

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: 辅助索引(单列,联和,前缀)

7.1 单列普通辅助索引

7.1.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;
![image](https://upload-images.jianshu.io/upload_images/16956686-8c8421524dca6291.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
注意:
以上操作不代表生产操作,我们不建议在一个列上建多个索引
同一个表中,索引名不能同名。
### 7.1.2 删除索引:
db01 [world]>alter table city drop index idx_name1;
                                        表名                 索引名

7.2 覆盖索引(联合索引)

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

7.3 前缀索引

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

7.4 唯一索引

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';


(0)

分享至