SQL语句优化方式

  • 不要使用*号进行查询操作,使用具体字段.

  • 索引

    • 在where子句和order by 涉及的字段上合理的添加索引.
  • where 子句优化

  • 避免在where子句中对null值进行判断,应对字段设置默认值

    1Select id from t where num is null 2可以对null值设置默认值为-1(根据自己的实际情况设置) 3判断null可以使用 4select id from t where num = -1
  • 避免在where子句中使用!= 或者<>操作符.

  • 尽量避免where子句中使用or 来连接条件

    1select id from t where num = 1 or num = 5 2/*可以优化为*/ 3select id from t where num = 1 4unicon all 5select id form t where num = 5
  • in 和not  in  也要慎用

    1/*连续条件*/ 2select id from t where num in (1,2,3) 3/*可以使用 between and */ 4select id from t where num between 1 and 3 5/*更多可以使用exists 代替 in*/ 6select num from a where num in (select num from t) 7/*替换语句*/ 8select num from a where EXISTS (select num from b where a.num = b.num)
  • 模糊查询SQL优化

  • 1 /*正常情况下,百分号在后面可以使用索引*/ 2 select nickname from t where nickname like 'DBA%' 3 /*百分号在前面,不能使用索引,解决方案.改写sql,添加reverse索引*/ 4 create index idx_t1_name on t1(reverse(name)) 5 select name from t1 where reverse(name) like reverse('%adc'); 6 /*前后都有百分号,这种情况一般不能使用索引.*/ 7 /*1.搜索条件字符串始终在字符串开始的固定位置出现,可以创建函数索进行优化,先创建subStr 函数索引,再使用like 'abc%'示例:*/ 8 create index idx_substr_t1_name on t1 (substr(name,5,10)); 9 select id, name ,name_type from t1 where substr(name, 5,10) like 'abc%'; 10 /*2.搜索条件始终在字符串结尾的某个固定位置出现,可以创建函数组合索引进行优化,先创建reverse + substr 组合函数索引,再使用like reverse '%abc'*/ 11 create index idx_t1_reverse_name on t1(reverse(substr(name,1,length(name)-4))); 12 13 select id,name,name_type from t1 where reverse(substr(name,1,length(name)-4)) like reverse('%abc') 14 15 /*3.搜索字符串再不固定位置出现,优化方案,先建立普通索引列,改写sql*/ 16 create index idx_t1_name on t1(name) 17 18 select id,name,name_type from t1 where name in (select name from t1 where name like '%abc%')
  • 避免在where子句中对字段的 '=' 左边进行函数,算数,或其他表达式运算

  • 不要使用select counut(*) from table ,这样不带任何条件的count会引起全表扫描, 可以使用count(1) 代替

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

常见SQL编写和优化

常见的SQL优化方式1.对查询进行优化,应尽量避免全表扫描,首先应考虑在where及orderby涉及的列上建立索引。2.应尽量避免在where子句中对字段进行null值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:selectidfromtwherenumisnul

mysql千万级大数据SQL查询优化

1.对查询进行优化,应尽量避免全表扫描,首先应考虑在where及orderby涉及的列上建立索引。2.应尽量避免在where子句中对字段进行null值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:selectidfromtwherenumisnull可以在num上设置默认值0,确保表中num列没有