查询优化 - 索引

索引:索引是一种特殊的文件(InnoDB数据表上的索引是表空间的一个组成部分),它们包含着对数据表里所有记录的引用指针。

 索引的使用

查看索引
show index from 表名;
创建索引
  • 如果指定字段是字符串,需要指定长度,建议长度与定义字段时的长度一致

  • 字段类型如果不是字符串,可以不填写长度部分

create index 索引名称 on 表名(字段名称(长度))
删除索引
drop index 索引名称 on 表名;
索引代码示例

创建测试表test_index

create table test_index(title varchar(10));

使用python程序(ipython也可以)通过pymsql模块 向表中加入十万条数据

from pymysql import connect

def main():
    # 创建Connection连接
    conn = connect(host='localhost', user='root', password='root', database='test')
    # 获得Cursor对象
    cursor = conn.cursor()
    # 插入10万次数据
    for i in range(100000):
        cursor.execute("insert into test_index values('ha-%d')" % i)
    # 提交数据
    conn.commit()

if __name__ == "__main__":
    main()
查询
开启运行时间监测
set profiling=1;
查找第1万条数据ha-99999
select * from test_index where title='ha-99999';
查看执行的时间
show profiles;
为表test_indextitle列创建索引title_index
create index title_index on test_index(title(10));
执行查询语句
select * from test_index where title='ha-99999';
再次查看执行的时间
show profiles;

  • 16
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值