首页 > 数据库技术 > 详细

139 MySQL索引

时间:2019-10-04 15:29:42      阅读:87      评论:0      收藏:0      [点我收藏+]

一、索引的概念

  • 索引就是键 -key

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

二、实例

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字段的数据查询的速度比较快。这就是键(索引)可以极大的加快查询速度

139 MySQL索引

原文:https://www.cnblogs.com/xichenHome/p/11622145.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!