sql语句的简单优化

来源:互联网 发布:.net java开发 编辑:程序博客网 时间:2024/06/06 18:40

常见的sql优化技巧

①通过变量的方式来设置参数

好:

1

stringsql = "select * from people p where p.id = ? ";

坏:

1

stringsql = "select * from people p where p.id = "+id;

数据库的SQL文解析和执行计划会保存在缓存中,但是SQL文只要有变化,就得重新解析。

“…where p.id = +id的方式在id值发生改变时需要重新解析,这会耗费时间。

②不要使用select *

好:

1

stringsql = "select people_name,pepole_age from people ";

坏:

1

stringsql = "select * from people ";

使用select *的话会增加解析的时间,另外会把不需要的数据也给查询出来,数据传输也是耗费时间的,

比如text类型的字段通常用来保存一些内容比较繁杂的东西,如果使用select *则会把该字段也查询出来。

③谨慎使用模糊查询

好:

1

stringsql = "select * from people p where p.id like 'parm1%' ";

坏:

1

stringsql = "select * from people p where p.id like '%parm1%' ";

当模糊匹配以%开头时,该列索引将失效,若不以%开头,该列索引有效。

④不要使用列号

好:

1

stringsql = "select people_name,pepole_age from people order by name,age";

坏:

1

stringsql = "select people_name,pepole_age from people order by 6,8";

使用列号的话,将会增加不必要的解析时间。

⑤优先使用UNION ALL,避免使用UNION

好:

1

stringsql = "select name from student

 union all

select name from teacher";

坏:

1

stringsql = "select name from student

union

select name from teacher";

UNION 因为会将各查询子集的记录做比较,故比起UNION ALL,通常速度都会慢上许多。一般来说,如果使用UNION ALL能满足要求的话,务必使用UNION ALL。还有一种情况,如果业务上能够确保不会出现重复记录。

⑥在where语句或者order by语句中避免对索引字段进行计算操作

好:

1

stringsql = "select people_name,pepole_age from people where create_date=date1 ";

坏:

1

stringsql = "select people_name,pepole_age from people where trunc(create_date)=date1";

当在索引列上进行操作之后,索引将会失效。正确做法应该是将值计算好再传入进来。

⑦使用not exist代替not in

好:

?

1

stringsql = "select * from orders where customer_name not exist (select customer_name from customer)";

坏:

?

1

stringsql = "select * from orders where customer_name not in(select customer_name from customer)";

如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。

⑧避免在索引列上做如下操作:

◆避免在索引字段上使用<>!=
◆避免在索引列上使用IS NULLIS NOT NULL
◆避免在索引列上出现数据类型转换(比如某字段是String类型,参数传入时是int类型)

当在索引列上使用如上操作时,索引将会失效,造成全表扫描。

⑨复杂操作可以考虑适当拆成几步

有时候会有通过一个SQL语句来实现复杂业务的例子出现,为了实现复杂的业务,嵌套多级子查询。造成SQL性能问题。对于这种情况可以考虑拆分SQL,通过多个SQL语句实现,或者把部分程序能完成的工作交给程序完成

10、表字段都设置为not null  有默认值

 

 

1.普通索引   添加INDEX
ALTER TABLE `table_name` ADD INDEX index_name ( `column` )

下面演示下给user表的name字段添加一个索引

2.主键索引   添加PRIMARY KEY
ALTER TABLE `table_name` ADD PRIMARY KEY ( `column` )

3.唯一索引    添加UNIQUE
ALTER TABLE `table_name` ADD UNIQUE ( `column` )

4.全文索引    添加FULLTEXT
ALTER TABLE `table_name` ADD FULLTEXT ( `column`)

5.如何添加多列索引
ALTER TABLE `table_name` ADD INDEX index_name ( `column1`, `column2`, `column3` )

0 0
原创粉丝点击