MySQL索引学习(100万数据做对比)

创建表

create table account
(
    id    int auto_increment
        primary key,
    name  varchar(11)   not null,
    money decimal(9, 2) not null
);

一、显示某个表所有索引信息

show index from account;

二、添加一个全文索引 (索引名字)列名

alter table shop.account add fulltext index `aa`(name)

索引名字是aa,列名是name,将aa包裹的是tab键上面的键

三、测试索引

这里用到一个:explain

分析sql执行的状况

现在我account表里有22条数据

执行sql

explain select * from account -- 非全文索引

结果

查了22列

用刚刚创建的索引查询

explain select * from account where match(`name`) against('wjdsg')

结果:

 现在我们往account插入100万条数据

delimiter $$   -- 表明以下是函数,函数标注
create function mack_data()  -- 创建函数名字
returns int     -- 返回值
begin   -- 函数开始
    declare num int default 1000000;  -- 定义变量
    declare i int default 0;    -- 定义变量
    while i<num do  -- 循环插入
        insert into account(name, money) VALUES (concat('wj',i),1000+i);
        set i=i+1;
    end while;
    return i;
end;    -- 函数结束
# 调用函数执行
select mack_data();

如果你创建函数如下错误:

This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its de....

可以执行:

set global log_bin_trust_function_creators=TRUE;

然后慢慢等,大概需要一分钟

 执行成功

数据多了,我们就可以开始测试索引

select * from account where name = 'wjdsg8888'

 执行时间1s多

这是我们看一下这条sql查了多少数据才找到`wjdsg8888`

explain select * from account where name = 'wjdsg8888'

现在我们再来创建一个索引

create index 索引名字 on account(name)
create index id_account_name on account(name)

 创建索引完,再来查询`wjdsg8888`

select * from account where name = 'wjdsg8888';

 质的飞跃

explain select * from account where name = 'wjdsg8888';

row=1

四、索引原则

1、索引不是越多越好:

我的建议是建表之前不需要加索引,当数据量超过500万,人感觉到慢了之后,再添加索引,速度还行就不要添加

2、不要对经常变动的数据加索引

3、索引一般加在常用来查询的字段

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

wjdsg

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

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

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

打赏作者

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

抵扣说明:

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

余额充值