MySQL数据库给表添加索引 | 您所在的位置:网站首页 › 使用index命令不能为数据表创建索引 › MySQL数据库给表添加索引 |
说明:当数据库中的记录数过多时,查询速度会显著变慢。此时可以给表创建索引,提高查询速度。 一、创建索引前我现在有一张表,有1000万条记录,根据username值,查询一条记录,测试下查询时间; select id, username, password, sex, email from user where username='zhangsan5000025';查询时间:25s 695ms (1)创建索引:给user表的username字段,添加索引,索引名为username_index,此过程会花费较长的时间(相较于查询); create index username_index on user(username);(2)查看索引:查看user表的索引; show index from user;(3)删除索引:删除user表的username_index索引; drop index username_index on user; 三、创建索引后创建索引后,再试下查询时间,可以看到查询速度有显著提升 select id, username, password, sex, email from user where username='zhangsan5000025';查询时间:73ms 需要知道以下这些: (1)MySQL的索引,底层是用B+Tree实现的; (2)索引并不是加的越多越好,添加索引会增加数据所占的空间,所以通常给查询频繁的字段添加索引; (未使用索引的数据大小) (加索引后的数据大小) (3)MySQL中,表的主键、唯一约束是自动生成的索引(其实也好理解,不建立索引,数据库怎么能在添加数据时,立刻检索到我们添加的数据是否唯一呢?); |
CopyRight 2018-2019 实验室设备网 版权所有 |