JAVA面试题 - 数据库(Mysql)

JAVA面试题 总目录篇

一条sql语句执行时间过长,应该如何优化?从哪些方面进行优化?

执行计划调优
语句调优
索引调优
设计调优
业务调优

你做过那些sql优化?

1、对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。
2、避免索引失效的情况。
3、任何地方都不要使用 select * from t ,用具体的字段列表代替“*”,不要返回用不到的任何字段。

索引在什么情况下会失效?

1、采用like模糊查询,且%在前面时,不走索引。
2、组合索引,不符合最左匹配原则时,不走索引。
3、索引列有函数处理或谓词运算,不走索引。
4、索引列有隐式转换,不走索引。
5、where子句中使用IS NULL或者IS NOT NULL,不走索引。
6、where子句中使用<>、!=、in、not in、exists、not exists ,不走索引。

详细说明:
1.采用like模糊查询,且%在前面时,不走索引。

alter table user add index my_index_name(name);    
select * from user where name like '%zhangsan%';  //不走索引
select * from user where name like '%zhangsan';  //不走索引
select * from user where name like 'zhangsan%';  //走索引

2.组合索引,不符合最左匹配原则时,不走索引。

alter table user add index my_index_name(name, age);
select * from user where age = 18;   //不走索引                                                          
select * from user where name='zhangsan';    //走索引
select * from user where name='zhangsan' and age=18;   //走索引

3.索引列有函数处理或谓词运算,不走索引。

alter table user add index my_index_name(name);
select * from user where upper(name)='ZHANGSAN';  //不走索引
alter table user add index my_index_age(age);
select * from user where age/2=9;  //不走索引
select * from user where age=9*2;  //走索引

这样的函数还有:to_char、to_date、to_number、trunc等

4.索引列有隐式转换,不走索引。

alter table user add index my_index_age(age); //age是int类型
select * from user where age='18’'; //不走索引
select * from user where age=18;  //走索引
alter table user add index my_index_name(name); //name是String类型
select * from user where name=zhangsan; //不走索引
select * from user where name='zhangsan';  //走索引

5.where子句中使用IS NULL或者IS NOT NULL,不走索引。

select * from user where name IS NULL;  //不走索引

6.where子句中使用<>、!=、in、not in、exists、not exists ,不走索引。

select * from user where name != 'zhangsan';  //不走索引
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值