SQL优化的常见手段

参考:https://www.cnblogs.com/wangzhengyu/p/10412499.htmlhttps://blog.csdn.net/micro_hz/article/details/83828012侵删!

SQL优化的常见手段:

1、在表中建立索引,优先考虑where、group by使用到的字段。

2、尽量避免是用select *,返回无用的字段会降低查询效率。因此,使用具体的字段,只返回需要的字段。例:

//优化前:
select * from table;
//优化后:
select name from table;

3、尽量避免使用 in 和 not in ,会导致数据库引擎放弃索引进行全表扫描。如下:

select name from table where id in (2,3);
select name from table1 where name in (select name from table2);

如果是连续数值,可以用between代替,如果是子查询,可以用exists代替,如:

select name from table where id between 2 and 3;
select name from table1 where exists (select name from table2 where table1.name = table2.name);

4、尽量避免使用or,会导致数据库引擎放弃索引进行全表扫描。

5、尽量避免在字段开头模糊查询,会导致数据库引擎放弃索引进行全表扫描。尽量在字段后面使用模糊查询。如下:

优化前:
select name from table where name like '%li%';
优化后:
select name from table where name like 'li%';

6、尽量避免进行null值的判断,会导致数据库引擎放弃索引进行全表扫描。可以给字段添加默认值0,对0值进行判断。如下:

优化前:
select name from table where score is null;
优化后:
select name from table where score=0;

7、尽量避免在where条件中等号的左侧进行表达式、函数操作,会导致数据库引擎放弃索引进行全表扫描。如下:

优化前:
select name from table where score/10 = 9;
优化后:
select name from table where score = 10*9;

8、当数据量大时,避免使用where 1=1的条件。通常为了方便拼装查询条件,我们会默认使用该条件,数据库引擎会放弃索引进行全表扫描。如下:

select name from table where 1=1;

优化方式:用代码拼装sql时进行判断,没where加where,有where加and。

9、count语句
count()与count(某个字段)的区别是count(某个字段)统计字段非null的行数。
count(1)与count()都是统计primary Key,效率一样,如果没有PK,全表扫描.
如果count(column) ,其中column为索引,count(column)和count(1)一样快,否则count(column)走全表扫描。

10、order by 语句
有序索引extra 显示Using Index的话,MySQL有序返回,效率非常高。
返回数据排序,Using file sort,使用排序算法在sort_buffer_size系统变量设置的内存排序区中进行排序,内存装不下在磁盘,然后合并结果。file sort优化,减少额外排序,创建合适索引,select * 改成指定的字段,减少排序区的使用。

11、group by语句
group by默认加了order by ,不用再加order by
group by如果不关系排序,可以 order by null禁止排序降低排序消耗。

12、limit 语句
指定的范围小可以先拿出key值再去查全部字段, 避免查太多数据。

select name from table limit 20,30; 

13、子查询
一般来说JOIN 比子查询效率高


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值