sql语句in查询怎么优化_sql语句的优化方式

大部分我们在刚从事后端工作时写的sql语句主要注重结果,并没有对他的执行效率进行考虑,只是单纯的完成自己手头上的任务,毕竟开发环境下 表中的数据量较少,执行起来也很快,并没有察觉到自己写的sql语句的执行效率,但是在面试过程 中,经常被问到sql语句如何优化的问题,下面我来介绍 一下常用的sql语句优化的方式。

d8939dcc7c2d3683814d90a0d2416f5a.png

1.为了提高查询效率,优先原则是避免全表扫描,在where子句的列以及order by涉及的列建立索引。 如: select * from A where name ='zhangsan' order by id ; 在这我们可以建立一个更高效的 联合 索引Inde x(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语句优化的方法,面试时没必要完全都要说出来,只需将自己知道的说出来几种即可,大家按照自己的理解来复述以上的观点, 用通俗易懂的话来叙述出来,会有更好的效果哦!

41350042f43f22808c8b75bad64308ce.png

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值