服务热线: 400 996 3338

为什么我的SQL比你的快

百家讲堂

刚开始写sql的时候或许我们不会在乎它的优化, 但到后来发现数据大导致服务器反应慢的时候就不得不重视了!

要提高SQL语句的执行效率,最常见的方法就是建立索引,以及尽量避免全表扫描。下面主要介绍几个查询语句实例:

1、避免在 where 子句中使用 or来连接条件。

如:select tell from user where name = ‘yang’ or name = 'heng'

这种情况,我们可以这样写:

select tell from user where name = 'yang' union all select id from user where name = 'heng'

2、少用 not in 或 in。

虽然对于 in 的条件会使用索引,不会全表扫描,但是在某些特定的情况,使用其他方法也许效果更好。

如:select title from guestbook where id in(1,2,3,4,5)

像这种连续的数值,我们可以使用 BETWEEN num1 AND num2,如:select title from guestbook where id between 1 and 5

3、避免在 where 子句中对字段进行函数操作。

如:select id from table where substring(name,1,4) = 'yang'

或 select id from table where datediff(day,date,'2014-12-16) >= 0

这两条语句中都对字段进行了函数处理,这样就是的查询分析器放弃了索引的使用。

建议这样:select id from table where name like 'yang%' 或 select id from table where date <= '2014-12-16' ,也就是说,不要在 where 子句中的 = 左边进行函数、算术运算或其他表达式运算。

4、注意 like 中通配符的使用。

下面的语句会导致全表扫描,尽量少用。如:

select email from tabel where name like '%zong%'或者select email from tabel where name like'%zong'

而下面的语句执行效率要快的多,因为它使用了索引:select email from tabel where name like 'zong%'

为什么我的SQL比你的快

5、避免在 where 子句中使用 != 或 <> 操作符。

如:select name from table where id <> 50, 数据库在查询时,对 != 或 <> 操作符不会使用索引,而对于 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,数据库才会使用索引。因此对于上面的查询,建议使用:

select name from table where id < 50 union all select name from table where id > 50

6、避免在 where 子句中对字段进行表达式操作。

如:select name from table where id/2 = 100 正确的写法应该是:select name from table where id = 100*2

7、在子查询中,用 exists 代替 in 是一个好的选择。

如:select name from a where id in(select id from b)

如果我们将这条语句换成下面的写法:select name from a where exists(select 1 from b where id = a.id) 这样,查询出来的结果一样,但是下面这条语句查询的速度要快的多。

以上说到的几点也不是必须要这样写, 建议在数据多的时候使用。

这几点只是sql优化大海中的几滴水, 要在程序这个世界里追求更完美, 我们还得不断猜想和实践!

咨询 电话

199 2665 9819

TOP

给我们留言

Copyright © 2009-2023 深圳市政元软件有限公司 版权所有 粤ICP备13085650号