索引
- 介绍:索引在
MySQL
中也叫做“键”,它是一种特殊的文件,它保存着数据表里所有记录的位置信息,更通俗的来说,数据库索引好比是一本书前的目录,能加快数据库的查询速度。 - 注意:
index
是MySQL
中的关键字,不要把key
定义为index
。 - 应用场景:当数据库中数据量大时,查找数据会变得很慢,我们就可以通过索引来提高数据库的查询效率。
查看表中已有索引
show index from 表名;
创建索引
alter table 表名 add index [索引名](列名, ...)
alter table gongfu add index i_name(name);
删除索引
alter table 表名 drop index 索引名;
show create table 表名;
shwo index from 表名;
show index form hero;
alter table hero drop index i_name;
验证索引查询的性能
create table(title varchar(10));
import pymysql
conn = pymysql.connect(host="localhost", port=3306, user="root",
password="1237894560", database="heima",charset="utf8")
cursor = conn.cursor()
sql = "insert into testindex value(%s)"
try:
for i in range(500000):
cursor.execute(sql, ['ha-' + str(i)])
conn.commit()
except Exception as err:
print("SQL操作失败,开始回滚", err)
conn.rollback()
finally:
cursor.close()
conn.close()
set profiling = 1;
select * from testindex where title="ha-499999";
show profiles;
alter table testindex add index i_title(title);
select * from testindex where title="ha-499999";
show profiles;
- 说明:很明显查询速度快了83倍左右(只是我的电脑上),如果没有
index
,查询会进行全盘扫描,直到找到结果,复杂度最大为n。
