MySQL索引

  • 索引的分类

    • 主键索引(primary key):唯一的标识,主键不可重复,只能有一个列作为主键
    • 唯一索引(unique key):避免重复的列出现,唯一索引可以重复,多个列可以都标识为唯一索引
    • 常规索引(key/index):默认的,index、key关键字来设置
    • 全文索引(fulltext):在特定的数据库引擎下才有(MyISAM),快速定位数据
  • 索引的使用

    • 创建表的时候给字段添加索引
    • 创建完毕后添加索引
  • 显示所有的索引信息:show index from 表名;

  • 添加一个全文索引:alter table 表名 add fulltext index 索引名(列名);

  • explain分析sql执行的状况

    • 非全文索引:explain select * from 表名;
    • 全文索引:explain select * from 表名 where match(索引名) against(值);
  • SQL插入100万条数据

    delimiter $$ -- 写函数之前必须写的标志
    create function mock_data()
    returns int
    begin
    	declare num int default 1000000;
    	declare i int default 0;
    	while i<num do
    	insert into `app_user`(`name`,`email`,`phone`,`sex`,`password`,`age`)
    	values(concat('用户',i),'123123@qq.com',
               concat('15'floor(rand()*(999999999-100000000)+100000000)),
               floor(rand()*2),uuid(),floor(rand()*100));
               set i = i+1;
    	end while;
    	return i;
    end;
    
    select mock_data();
    
  • 查询上表中的数据

    -- 未添加索引
    select * from `app_user` where `name` = '用户9999'; -- 1.098sec
    
    -- 添加索引
    -- create index 索引名 on 表(字段)
    -- 索引名:id_表名_字段名
    create index id_app_user_name on `app_user`(`user`);
    select * from `app_user` where `name` = '用户9999'; -- 0.001sec
    
  • 索引原则

    • 索引不是越多越好
    • 不要对进程变动的数据加索引
    • 小数据量的表不需要加索引
    • 索引一般加载常用来查询的字段上
  • 索引的数据结构:http://blog.codinglabs.org/articles/theory-of-mysql-index.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Remote_Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值