在多表联合查询中,当使用Ordered提示改变SQL执行计划之后,通常我们很难再次控制结果集中进一步Join的顺序.
这时候我们可以使用Oracle提供的另外一个Hints: Leading 提示.
这个Hints在Oracle9i中的含义为:
The LEADING hint causes Oracle to use the specified table as the first table in the join order.
If you specify two or more LEADING hints on different tables, then all of them are ignored. If you specify the ORDERED hint, then it overrides all LEADING hints.
通过Leading 和 use_hash 提示连用,我们可以巧妙的影响SQL中表和结果集的Join顺序.
我们通过如下示例看一下这个提示是如何影响SQL执行的:
SQL> SELECT /*+ leading(t_max) use_hash(t_max t_middle) */ COUNT (*)
2 FROM t_small, t_max, t_middle
3 WHERE t_small.object_id = t_middle.object_id
4 AND t_middle.object_id = t_max.object_id
5 /
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE (Cost=262 Card=1 Bytes=12)
1 0 SORT (AGGREGATE)
2 1 HASH JOIN (Cost=262 Card=400 Bytes=4800)
3 2 HASH JOIN (Cost=225 Card=113776 Bytes=910208)
4 3 TABLE Access (FULL) OF 'T_MAX' (Cost=151 Card=113792 Bytes=455168)
5 3 TABLE ACCESS (FULL) OF 'T_MIDDLE' (Cost=39 Card=28447 Bytes=113788)
6 2 TABLE ACCESS (FULL) OF 'T_SMALL' (Cost=2 Card=100 Bytes=400)
我们看到,通过这两个Hints的联合使用,该查询首先对T_MAX和T_MIDDLE表进行HASH JOIN,再以这个结果集同T_SMALL进行HASH JION.
单纯通过Ordered和USE_HASH提示通常是达不到这个效果的:
SQL> SELECT /*+ ordered use_hash(t_max t_middle) */ COUNT (*)
2 FROM t_max, t_middle,t_small
3 WHERE t_small.object_id = t_middle.object_id
4 AND t_middle.object_id = t_max.object_id
5 /
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE (Cost=228 Card=1 Bytes=12)
1 0 SORT (AGGREGATE)
2 1 HASH JOIN (Cost=228 Card=400 Bytes=4800)
3 2 TABLE ACCESS (FULL) OF 'T_SMALL' (Cost=2 Card=100 Bytes=400)
4 2 HASH JOIN (Cost=225 Card=113776 Bytes=910208)
5 4 TABLE ACCESS (FULL) OF 'T_MAX' (Cost=151 Card=113792 Bytes=455168)
6 4 TABLE ACCESS (FULL) OF 'T_MIDDLE' (Cost=39 Card=28447 Bytes=113788)
这是Leading Hints在Oracle9i中的一个非凡用法.