在多表聯合查詢中當使用Ordered提示改變SQL執行計劃之後通常我們很難再次控制結果集中進一步Join的順序
這時候我們可以使用Oracle提供的另外一個Hints: Leading 提示
這個Hints在Oraclei中的含義為:
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 (*)
FROM t_small t_max t_middle
WHERE t_smallobject_id = t_middleobject_id
AND t_middleobject_id = t_maxobject_id
/
Execution Plan
SELECT STATEMENT Optimizer=CHOOSE (Cost= Card= Bytes=)
SORT (AGGREGATE)
HASH JOIN (Cost= Card= Bytes=)
HASH JOIN (Cost= Card= Bytes=)
TABLE ACCESS (FULL) OF T_MAX (Cost= Card= Bytes=)
TABLE ACCESS (FULL) OF T_MIDDLE (Cost= Card= Bytes=)
TABLE ACCESS (FULL) OF T_SMALL (Cost= Card= Bytes=)
我們看到通過這兩個Hints的聯合使用該查詢首先對T_MAX和T_MIDDLE表進行HASH JOIN再以這個結果集同T_SMALL進行HASH JION
單純通過Ordered和USE_HASH提示通常是達不到這個效果的:
SQL> SELECT /*+ ordered use_hash(t_max t_middle) */ COUNT (*)
FROM t_max t_middlet_small
WHERE t_smallobject_id = t_middleobject_id
AND t_middleobject_id = t_maxobject_id
/
Execution Plan
SELECT STATEMENT Optimizer=CHOOSE (Cost= Card= Bytes=)
SORT (AGGREGATE)
HASH JOIN (Cost= Card= Bytes=)
TABLE ACCESS (FULL) OF T_SMALL (Cost= Card= Bytes=)
HASH JOIN (Cost= Card= Bytes=)
TABLE ACCESS (FULL) OF T_MAX (Cost= Card= Bytes=)
TABLE ACCESS (FULL) OF T_MIDDLE (Cost= Card= Bytes=)
這是Leading Hints在Oraclei中的一個特殊用法
From:http://tw.wingwit.com/Article/program/Oracle/201311/18458.html