mengxuyang 发表于 2007-4-6 08:35:37

SQL语句的优化二

正确使用INDEX的SQL

如果和查询条件相关的column上有建index,以下几点能帮助SQL正确的使用index 。

        避免显式或隐含的类型转换。
where子句中存在数据类型隐形转换的,如用Numeric 型和 Int型的列的比较时,不能使用index。

        WHERE子句中任何对列的操作都将无法使用index,它包括数据库函数、计算表达式等等,所以要尽量减少在=左边的列的运算。如:
BF:select staff_no, staff_name from staff_member where salary*2 <= 10000;
RP:select staff_no, staff_name from staff_member where salary <= 5000;

        WHERE子句中使用不等于(<>)运算的,将无法使用index。可以用union all改写。如:
BF:select staff_no, staff_name from staff_member where dept_no<>2001;
RP:select staff_no, staff_name from staff_member where dept_no < 2001
Union all
select staff_no, staff_name from staff_member where dept_no > 2001;
Oralce中可以考虑使用函数索引。

        WHERE子句中使用substr字符串函数的,将无法使用index,可以用like改写。如:
BF:select staff_no, staff_name from staff_member where substr(last_name,1,4)=’FRED’;
RP:select staff_no, staff_name from staff_member where last_name like ’FRED%’;

        WHERE子句中‘%’通配符在第一个字符的,将无法使用index。如:
select staff_no, staff_name from staff_member where first_name like ‘%DON’;
这种情况的优化方式比较复杂,在后面有关index优化的内容中我们介绍一种在oracle中使用反向索引的优化方式。

        LIKE语句后面不能跟变量,否则也不会使用索引。
where Prod_name like :v_name || '%' -- 不会使用索引
如果一定要使用变量,可以使用如下技巧:
where Prod_name between :v_name and :v_name || chr(255) -- 会使用索引

        WHERE子句中使用IS NULL和IS NOT NULL不会使用索引。好的设计习惯是表中尽量不使用允许为空的字段,可以根据业务逻辑,将字段设为NOT NULL的同时,提供一个DEFAULT值。另外,当表中建有索引的字段包含NULL时,索引的效率会降低。

        WHERE子句中使用字符串连接(||)的,将无法使用index。我们应该改写这个查询条件。如:
BF:select staff_no, staff_name from staff_member
where first_name||' '||last_name ='Beill Cliton';
RP:select staff_no, staff_name from staff_member
where first_name = ‘Beill’
and last_name ='Cliton';

wmzmd 发表于 2007-11-4 22:57:32

路过,学习!

mufeng00 发表于 2022-9-1 15:26:28

学习一下
页: [1]
查看完整版本: SQL语句的优化二