创建表
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万,人感觉到慢了之后,再添加索引,速度还行就不要添加