您的位置:首页 > 数据库

如何提高SQL语言的查询效率?

2006-09-28 11:24 246 查看
如何提高SQL语言的查询效率?
问:请问我如何才能提高SQL语言的查询效率呢?

答:这得从头说起:

由于SQL是面向结果而不是面向过程的查询语言,所以一般支持SQL语言的大型关系型数据库都使用一个基于查询成本的优化器,为即时查询提供一个最佳的执行策略。对于优化器,输入是一条查询语句,输出是一个执行策略。
一条SQL查询语句可以有多种执行策略,优化器将估计出全部执行方法中所需时间最少的所谓成本最低的那一种方法。所有优化都是基于用记所使用的查询语句中的where子句,优化器对where子句中的优化主要用搜索参数(Serach Argument)。

搜索参数的核心思想就是数据库使用表中字段的索引来查询数据,而不必直接查询记录中的数据。

带有 =、<、<=、>、>= 等操作符的条件语句可以直接使用索引,如下列是搜索参数:
emp_id = "10001" 或 salary > 3000 或 a =1 and c = 7

而下列则不是搜索参数:
salary = emp_salary 或 dep_id != 10 或 salary * 12 >= 3000 或 a=1 or c=7

应当尽可能提供一些冗余的搜索参数,使优化器有更多的选择余地。请看以下3种方法:

第一种方法:
select employee.emp_name,department.dep_name from department,employee where (employee.dep_id = department.dep_id) and (department.dep_code='01') and (employee.dep_code='01');

它的搜索分析结果如下:
Estimate 2 I/O operations
Scan department using primary key
for rows where dep_code equals '01'
Estimate getting here 1 times
Scan employee sequentially
Estimate getting here 5 times


第二种方法:
select employee.emp_name,department.dep_name from department,employee where (employee.dep_id = department.dep_id) and (department.dep_code='01');

它的搜索分析结果如下:
Estimate 2 I/O operations
Scan department using primary key
for rows where dep_code equals '01'
Estimate getting here 1 times
Scan employee sequentially
Estimate getting here 5 times


第一种方法与第二种运行效率相同,但第一种方法最好,因为它为优化器提供了更多的选择机会。

第三种方法:
select employee.emp_name,department.dep_name from department,employee where (employee.dep_id = department.dep_id) and (employee.dep_code='01');

这种方法最不好,因为它无法使用索引,也就是无法优化……

使用SQL语句时应注意以下几点:

1、避免使用不兼容的数据类型。例如,Float和Integer,Char和Varchar,Binary和Long Binary不兼容的。数据类型的不兼容可能使优化器无法执行一些本可以进行的优化操作。例如:

select emp_name form employee where salary > 3000;

在此语句中若salary是Float类型的,则优化器很难对其进行优化,因为3000是个整数,我们应在编程时使用3000.0而不要等运行时让DBMS进行转化。

2、尽量不要使用表达式,因它在编绎时是无法得到的,所以SQL只能使用其平均密度来估计将要命中的记录数。

3、避免对搜索参数使用其他的数学操作符。如:

select emp_name from employee where salary * 12 > 3000;

应改为:

select emp_name from employee where salary > 250;

4、避免使用 != 或 <> 等这样的操作符,因为它会使系统无法使用索引,而只能直接搜索表中的数据。

 
→我是小木鱼(Lag)
写于2000年12月16日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: