索引在MySQL中也叫做“键”,它是一个特殊的文件,它保存着数据表里所有记录的位置信息,更通俗的来说,数据库索引好比是一本书前面的目录,能加快数据库的查询速度。
查看表中已有索引:
show index from 表名;
说明:
索引的创建:
-- 创建索引的语法格式 -- alter table 表名 add index 索引名[可选](列名, ..) -- 给name字段添加索引 alter table class add index cls_name (name);
说明:
索引的删除:
-- 删除索引的语法格式 -- alter table 表名 drop index 索引名 -- 如果不知道索引名,可以查看创表sql语句 alter table class drop index cls_name;
向表中插入十万条数据:
from pymysql import connect def main(): # 创建Connection连接 conn = connect(host=‘localhost‘,port=3306,database=‘python‘,user=‘root‘,password=‘mysql‘,charset=‘utf8‘) # 获得Cursor对象 cursor = conn.cursor() # 插入10万次数据 for i in range(100000): cursor.execute("insert into test_index values(‘ha-%d‘)" % i) # 提交数据 conn.commit() if __name__ == "__main__": main()
验证索引性能操作:
-- 开启运行时间监测: set profiling=1; -- 查找第1万条数据ha-99999 select * from test_index where title=‘ha-99999‘; -- 查看执行的时间: show profiles; -- 给title字段创建索引: alter table test_index add index (title); -- 再次执行查询语句 select * from test_index where title=‘ha-99999‘; -- 再次查看执行的时间 show profiles;
联合索引又叫复合索引,即一个索引覆盖表中两个或者多个字段,一般用在多个字段一起查询的时候。
-- 创建teacher表 create table teacher ( id int not null primary key auto_increment, name varchar(10), age int ); -- 创建联合索引 alter table teacher add index (name,age);
联合索引的好处:
在使用联合索引的时候,我们要遵守一个最左原则,即index(name,age)支持 name 、name 和 age 组合查询,而不支持单独 age 查询,因为没有用到创建的联合索引。
-- 下面的查询使用到了联合索引 select * from stu where name=‘张三‘ -- 这里使用了联合索引的name部分 select * from stu where name=‘李四‘ and age=10 -- 这里完整的使用联合索引,包括 name 和 age 部分 -- 下面的查询没有使用到联合索引 select * from stu where age=10 -- 因为联合索引里面没有这个组合,只有 name | name age 这两种组合
说明:
优点:
缺点:
使用原则:
原文:https://www.cnblogs.com/abysschen/p/12495252.html