两条SQL语句优化的规则

下面是两条平时接触频率很高的SQL语句优化规则,但是自己写SQL语句时经常漏下,因此摘录:

1、执行连接时使用完全限定的表引用,避免数据库去搜索哪一列属于哪个表

    在查询中包含表别名,并在查询中使用每个表的别名,这样数据库就不用检索每一列属于哪个表从而提高语句的执行效率。

   下面是实例:

  

1 select p.name, pt.name, description, price
2  from products p, product_types pt
3 where p.product_type_id = pt.product_type_id
4 --0.093秒
5 
6 select p.name, pt.name, p.description, p.price
7  from products p, product_types pt
8 where p.product_type_id = pt.product_type_id
9 --0.047秒

2.用EXISTS代替DISTINCT语句

  distinct用于去除重复的行,但是由于存在排序等操作,所以此语句的执行效率较低,在实际工作中应该避免使用,而应该尽量使用来EXISTS来代替。下面是实例

  

 1 --Bad
 2 select distinct p.product_id, p.name
 3   from products p, purchases pch
 4  where p.product_id = pch.product_id;
 5 
 6 --GOOD
 7   select p.product_id, p.name
 8     from products p
 9    where exists
10         (select 1 
11           from purchases a 
12          where a.product_id = p.product_id);

不过要注意的是优化原则2一般只是使用在需要检索一个表的信息中。

另外补充一点对外连接的说明:

   (1).(+)符号一般放在包含空值相反的一边。

posted @ 2012-10-14 21:11  原想  阅读(182)  评论(0编辑  收藏  举报