刨根问底:MySQL索引篇之千万级数据实战测试

今天中午我这边只有半个小时时间,再过半个小时,得带着孩子去我妈那吃饭,就拿我给学生讲的案例,给大家直入主题讲一下吧…

  1. MySQL索引创建

先说明一个问题啊,如果你创建数据表时创建了主键,此时主键列会自动创建索引

-- 创建索引的语法格式
-- alter table 表名 add index 索引名[可选](列名, ..)
-- 给name字段添加索引
alter table classes add index my_name (name);
  1. 索引删除
-- 删除索引的语法格式
-- alter table 表名 drop index 索引名
alter table classes drop index my_name;

-- 备注:如果不知道索引名,可以查看创表sql语句
show create table classes;
  1. 特殊索引–联合索引说明:

3.1. 联合索引又叫复合索引,即一个索引覆盖表中两个或者多个字段,一般用在多个字段一起查询的时候
3.2 减少磁盘空间开销,因为每创建一个索引,其实就是创建了一个索引文件,那么会增加磁盘空间的开销。
3.3 联合索引的最左原则:在使用联合索引的时候,我们要遵守一个最左原则,即index(name,age)支持 name 、name 和 age 组合查询,而不支持单独 age 查询,因为没有用到创建的联合索引。

  • 联合索引的创建
-- 创建联合索引
alter table teacher add index (name,age);
  • 假设我们已经创建了(name, 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 这两种组合
  1. 接下来,我们展示一个索引实战案例 – 对比查询效率提升:
    我媳妇儿,又派小家伙过来催我了,…时间关系我这边就使用我上课时给学生讲的案例了:
# 1. 创建测试表testindex:
create table test_index(title varchar(10));
# 2.  向数据表中写入数据
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(10000000):
        cursor.execute("insert into test_index values('ha-%d')" % i)
    # 提交数据
    conn.commit()

if __name__ == "__main__":
    main()

# 3. 开启运行时间监测:
set profiling=1;
# 4. 查找第1000万条数据ha-99999999  (没有索引的情况)
select * from test_index where title='ha-99999999';
# 5. 查看执行的时间:
show profiles;
# 6. 给title字段创建索引:
alter table test_index add index (title);
# 7. 再次执行查询语句           (索引已经创建的情况)
select * from test_index where title='ha-99999999';
# 8. 再次查看执行的时间
show profiles;
  • 未建立索引的情况下查询时间:
    在这里插入图片描述
  • 建立索引之后的数据查询时间:
    在这里插入图片描述
    对比计算:
    在这里插入图片描述

总结:本次测试结果,创建索引查询与无索引查询对比之下效率提升105倍。

走走走,整29分钟,带着孩子去我妈家蹭饭去了…
都看到这了,点赞关注不迷路哦。。。

猜你喜欢

转载自blog.csdn.net/qq_41475067/article/details/115414164