索引
show index from 表名;
- 创建索引
- 如果指定字段是字符串,需要指定长度,建议长度与定义字段时的长度一致。
- 字段类型如果不是字符串,可以不填写长度部分
create index 索引名称 on 表名(字段名称(长度))
drop index 索引名称 on 表名;
索引创建案例
create table test(title varchar(10))
from pymysql import connect
def main():
conn = connect(host='localhost', port=3306, database='mysql', user='root', passwd='root', charset='utf8')
cursor = conn.cursor()
for i in range(100000):
cursor.execute("insert into test values('fml-%d')"%i)
conn.commit()
if __name__ == '__main__':
main()

查询
set profiling=1;

select * from test where title='fml-99999';

show profiles;

create index title_index on test(title(10));
select * from test where title='fml-99999';

show profiles;

适合建立索引的情况
- 主键自动建立索引
- 频繁作为查询条件的字段应该建立索引
- 查询中与其他表关联的字段,外键关系建立索引
- 在高并发的情况下创建复合索引
- 查询中排序的字段,排序字段若通过索引去访问将大大提高排序速度 (建立索引的顺序跟排序的顺序保持一致)
不适合建立索引的情况
- 频繁更新的字段不适合建立索引
- where条件里面用不到的字段不创建索引
- 表记录太少,当表中数据量超过三百万条数据,可以考虑建立索引
- 据重复且平均的表字段,比如性别,国籍