mysql 索引

自己在mysql 上体验一下索引

登录

mysql -u root -p 123;
//  root 为账号,123是密码。这是我的,你们自己输自己的。

创建一个数据库,用于测试

create database test_index;
// 创建了一个名为 test_index的数据库;

然后创建一张表

create table book(
id mediumint primary key not null,
price tinyint,
author varchar(1),
publisher varchar(1)
);

// 查看一下表是不是按我们预期定义
desc book;

然后往数据库中插入数据。

  • 通过自己造了100W条数据。时间有点久,好像要一个多小时才能全部插入数据库。
import  pymysql
import random
# 连接数据库   这里的用户名,密码和数据库要改成自己电脑的。
connect=pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123',
    db='test_index',
    charset='utf8'
)
cursor=connect.cursor()



for i in range(1000000):
    price=random.uniform(0,100)
    author=(chr)(random.randint(0,25)+ord('A'))
    publisher=(chr)(random.randint(0,25)+ord('a'))
    # print(price,author,publisher)
    order="insert into book(id,price,author,publisher) values(%d,%.3f,'%s','%s')"%(i,price,author,publisher)
    # print(order)
    try:
        cursor.execute(order)
        connect.commit()
    except Exception:
        print("发生异常",Exception,"错误命令",order)
        connect.rollback()
cursor.close()
connect.close()

然后就是开始干正事了,试试索引。

先看看没加索引查询

// 查询单价在[30,50]的书有几本
select count(*) from book where price >=30 and price <= 50;
// 查看作者为A 的书有几本
select count(*) from book where author = 'A';

两次查询基本都是要0.3秒。
在这里插入图片描述

普通索引
// 为price列创建普通索引
create index index_price on book(price);
select count(*) from book where price >=30 and price <= 50;
// 为author列创建普通索引 
create index index_author on book(author);
select count(*) from book where author = 'A';

可以发现建立索引后时间的确是变短了。
在这里插入图片描述

查看表当前有哪些索引
// 这两个都可以查看指定表的定义的索引。
show index from book;
show keys from book;

当前表索引

删除索引
// 删除之前插入的索引
drop index index_price on book;
drop index index_author on book;
  • 可以看到,在100w的数据量下,有无索引就可以差数十倍。如果上亿条的话差距会更明晰。但是,创建索引也会消耗一定的空间和时间的。
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值