JAVA面试题 - 数据库(Mysql)
一条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; //不走索引