sql优化常见知识点(转)

近期,我们对之前编写的数据库脚本进行了全面的自查,从数据库的性能方面考虑,将脚本里面的很多SQL语句进行了优化。对于一条SQL语句来说,索引的使用是否正确将直接影响到数据库的性能,因此,对索引使用方法的优化是数据库性能优化的重点。本文对常用的数据库索引优化语句进行了总结,可供相关的开发人员参考。

在本文中,使用如下的表tb_test作为示例进行说明:

create table tb_test
(
    id       int             not null,
    age      int             not null, 
    name     varchar(30)     not null,
    addr     varchar(50)     not null
);
create unique index idx1_tb_test on tb_test(id);
create        index idx2_tb_test on tb_test(name);
create        index idx3_tb_test on tb_test(addr);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

索引优化建议 
1.对索引列进行计算 
例如,我们想要将表tb_test中id大于100的数据记录中的age和name查找出来。

正确的SQL语句是:

select age,name from tb_test where id > 1*100;

不建议采用的SQL语句是:

select age,name from tb_test where id/100 > 1;

2.对索引列进行拼接 
例如,我们想要将表tb_test中name为“zhou”、addr为“CQ”的记录中的id和age查找出来。

正确的SQL语句是:

select id,age from tb_test where name=’zhou’ and addr=’CQ’;

不建议采用的SQL语句是:

select id,age from tb_test where concat(name,’ ‘,addr) = ‘zhou CQ’;

3.在索引列上is null或is not null的使用 
例如,我们想要将表tb_test中id大于等于“0”的记录中的age查找出来。

正确的SQL语句是:

select age from tb_test where id >= 0;

不建议采用的SQL语句是:

select age from tb_test where id is not null;

4.在索引列上or的使用 
例如,我们想要将表tb_test中id等于101或102的记录中的age和name查找出来。

正确的SQL语句(使用union)是:

select age,name from tb_test where id = 101 union select age,name from tb_test where id = 102;

不建议采用的SQL语句(使用or)是:

select age,name from tb_test where id = 101 or id = 102;

5.尽可能避免索引列在like的首字符使用通配符 
例如,我们想要将表tb_test中name匹配“zho”的记录中的id和age查找出来。

正确的SQL语句是:

select id,age from tb_test where name like ‘zho%’;

不建议采用的SQL语句是:

select id,age from tb_test where name like ‘%ho%’;

6.复合索引的使用 
如果我们建立的索引是复合索引,那么必须使用到该索引中的第一个字段作为条件时才能保证系统使用该索引。

例如,我们在表tb_test上新建了如下索引:

create index idx4_tb_test on tb_test(id,name,addr);

以上索引idx4_tb_test相当于建立了index(id)、index(id,name)、index(id,name,addr) 这3个索引。在SQL语句的where条件中单独使用name或addr时不会使用到该索引,必须使用id时才会使用到该索引。

总结 
在我们编写的SQL语句中,不正确地使用索引列可能会导致索引不被使用,而进行全表扫描,极大地降低了数据库的性能。因此,学习正确的索引的使用方法实在是很有必要的。

但是,需要指出的是,本文中提到的数据库索引的优化语句必须要在操作大量数据时才能显示出效果。在编写数据库脚本之前,大家可以先评估一下系统的数据量,看是否有必要在SQL优化上花费大量的时间。

猜你喜欢

转载自blog.csdn.net/qq_36381855/article/details/80946693
今日推荐