139 MySQL索引

1、索引的概念

  • 索引就是键 -keypython

    1)键 是添加给数据库表的 字段 的
    2)给表建立 键 后,该表不只会形参 表结构、表数据,还有 键的B+结构图
    3)键的结构图是须要维护的,在数据完成增、删、改操做时,只要影响到有键的字段,结构图都要维护一次
        因此建立键后必定会下降 增、删、改 的效率
    4)键能够极大的加快查询速度(开发需求中,几乎业务都和查有关系)
    5)创建键的方式:主键、外键、惟一键、index

2、实例

import pymysql
from pymysql.cursors import DictCursor

1.建立数据库链接对象
conn = pymysql.connect(user='root', passwd='root', db='oldboy')
cursor = conn.cursor(DictCursor)

2.先建立两张表无索引的a1
sql1 = """create table a1(
    id int primary key auto_increment,
    x int,
    y int
)"""
cursor.execute(sql1)
# 创建有索引的a2
sql2 = """create table a2(
    id int primary key auto_increment,
    x int,
    y int,
    index(x)
)"""
cursor.execute(sql2)


3.每一个表插入5000条数据
import random
for i in range(1, 5001):
    x = i
    y = random.randint(1, 5000)
    cursor.execute('insert into a1(x, y) values(%s, %s)', (x, y))
    cursor.execute('insert into a2(x, y) values(%s, %s)', (x, y))

conn.commit()

4.查询a1的id为4975的记录所用的时间
import time
b_time = time.time()
sql = 'select * from a1 where id=4975'
cursor.execute(sql)
e_time = time.time()
print(e_time - b_time)
# 结果:0.0010142326354980469

5.查询a1的x为4975的记录所用的时间
b_time = time.time()
sql = 'select * from a1 where x=4975'
cursor.execute(sql)
e_time = time.time()
print(e_time - b_time)
#结果:0.0019969940185546875

6.查询a2的id为4975的记录所用的时间
b_time = time.time()
sql = 'select * from a2 where x=4975'
cursor.execute(sql)
e_time = time.time()
print(e_time - b_time)
#结果:0.0009992122650146484

重点:从以上的a1和a2表的数据查询速度来看,很明显a2表中有索引的x字段的数据查询的速度比较快。这就是键(索引)能够极大的加快查询速度mysql

相关文章
相关标签/搜索