mysql 索引优化查询使用测试

本文通过创建测试表和大量数据,深入探讨了MySQL中不同查询条件对索引使用的影响,包括LIKE操作符、否定操作、函数使用、OR与AND操作符等场景,为数据库查询优化提供了实践指导。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


mysql 索引优化查询测试

 

 

**************************

测试表

 

字段:id、name、age、distance

 

插入10万条数据

drop procedure if exists hh;

delimiter //
create procedure hh()
begin
  declare i int default 1;
  declare count int default 100000;
	
  while i<=count do
    insert into test(id,name,age,distance) values(i,concat('gtlx ',i),(i%20)+10,round(rand()*1000)+100);
	set i=i+1;
  end while;
end //
delimiter ;

call hh();

 

 

**************************

like 操作符

 

在name、age列上建立复合索引 name_age:name在前,age在后

 

select * from where name like "gtlx 2%";

       

说明:该语句使用了索引name_age

 

select * from where name like "gtlx%";

      

说明:由于匹配的列过多,没有使用索引

 

select * from where name like "%gtlx";

      

说明:该select语句没有使用索引

 

 

**************************

否定操作:not、!=

 

select * from test where name ="gtlx";使用索引

select * from test where not name="gtlx";not否定操作不使用索引

select * from test where name!="gtlx";否定操作!= 不使用索引

      

 

 

**************************

索引列上使用函数、计算表达式不使用索引

 

select * from test where age>20;匹配数据过多,不使用索引

select * from test where (age-2)>20;索引列上使用计算表达式,不使用索引

select * from test where round(age)>20;索引上使用函数,不使用索引

      

 

 

**************************

or 操作符:两边索引列都有索引使用索引

 

查询语句:select * from test where name="gtlx" or age>30;

 

只在age列上建立索引:不使用索引

      

 

分别在name、age列上建立索引:使用索引

      

 

在name、age列上建立复合索引:不使用索引

      

 

 

**************************

and 操作符

 

查询语句:

select * from where name="gtlx" and age>30;使用索引

select * from where age>30 and name="gtlx";使用索引

      

说明:and 索引列的顺序不影响索引的使用

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值