大部分我们在刚从事后端工作时写的sql语句主要注重结果,并没有对他的执行效率进行考虑,只是单纯的完成自己手头上的任务,毕竟开发环境下表中的数据量较少,执行起来也很快,并没有察觉到自己写的sql语句的执行效率,但是在面试过程中,经常被问到sql语句如何优化的问题,下面我来介绍一下常用的sql语句优化的方式。
1.为了提高查询效率,优先原则是避免全表扫描,在where子句的列以及order by涉及的列建立索引。
如:select * from A where name =‘zhangsan’ order by id ; 在这我们可以建立一个更高效的 联合索引Index(name,id);
2.不要使用select * from table这样的语句,要用具体的列名代替“*”,避免全表扫描。
3.模糊查询时候的优化。如:
优化前:select id,name from A where name like “%张%”;这样写的话,一定会走全表扫描,效率很低;
优化后:select id,name from A where name like “张%”;
4.尽量避免在where子句中使用 != 、< 、>操作符号,不然还是走全表扫描。
5.尽量避免在where子句中使用 is null 或者 is not null 这样的,否则会进行全表扫描。我们可以在设计表字段时候给字段设置为默认值0,不要设置为NULL。
6.where子句中尽量避免使用“or”,我们可以使用union all 来替换,如果使用“or”,索引就会失效而会全表扫描。如:
优化前:select id from A where age=1 or age=2;
优化后:select id from A where age=1 union all select id from A where age=2;
7.where子句中尽量少用in 或者 not in ,不然的话,会丢弃索引进行全表扫描。我们可以 between 替换in 。如:
优化前:select id from A where age in (1,2,3);
优化后:select id from A where age between 1 and 3;
8.where 子句中尽量避免对字段进行函数操作,否则会放弃索引进行全表扫描。如:
优化前:select id from A where year(createtime) <2020;
优化后:select id from A where createtime < ‘2020-01-01’;
9.exist 代替 in 如:
优化前:select * from A where id in ( select id from B ) ;
优化后:select * from A where id exists ( select 1 from A.id= B.id );
10.使用join 来代替子查询。如:
优化前:select * from A where exists (select * from B where id>=3000 and A.id=B.id);
优化后:select * from A inner join B on A.id=B.id where b.id>=3000;
以上就是常用的sql语句优化的方法,面试时没必要完全都要说出来,只需将自己知道的说出来几种即可,大家按照自己的理解来复述以上的观点,用通俗易懂的话来叙述出来,会有更好的效果哦!