139 MySQL indexes

First, the concept of index

  • Index is the key -key

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

Second, examples

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

Key : From the above data query speed table a1 and a2, it is clear a2 x speed data table has an index query field faster. This is the key (index) can greatly speed up queries

Guess you like

Origin www.cnblogs.com/xichenHome/p/11622145.html