17. 使用表的别名(alias)
当在sql语句中连接多个表时, 请使用表的别名并把别名前缀于每个column上.这样一来,就可以减少解析的时间并减少那些由column歧义引起的语法错误.
(译者注: column歧义指的是由于sql中不同的表具有相同的column名,当sql语句中出现这个column时,sql解析器无法判断这个column的归属)
18. 用exists替代in
在许多基于基础表的查询中,为了满足一个条件,往往需要对另一个表进行联接.在这种情况下, 使用exists(或not exists)通常将提高查询的效率.
低效:
select *
from emp (基础表)
where empno > 0
and deptno in (select deptno
from dept
where loc = ‘melb’)
高效:
select *
from emp (基础表)
where empno > 0
and exists (select ‘x’
from dept
where dept.deptno = emp.deptno
and loc = ‘melb’)
(译者按: 相对来说,用not exists替换not in 将更显著地提高效率,下一节中将指出)
19. 用not exists替代not in
在子查询中,not in子句将执行一个内部的排序和合并. 无论在哪种情况下,not in都是最低效的 (因为它对子查询中的表执行了一个全表遍历). 为了避免使用not in ,我们可以把它改写成外连接(outer joins)或not exists.
例如:
select …
from emp
where dept_no not in (select dept_no
from dept
where dept_cat=’a’);
为了提高效率.改写为:
(方法一: 高效)
select ….
from emp a,dept b
where a.dept_no = b.dept(+)
and b.dept_no is null
and b.dept_cat(+) = ‘a’
(方法二: 最高效)
select ….
from emp e
where not exists (select ‘x’
from dept d
where d.dept_no = e.dept_no
and dept_cat = ‘a’);
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器