1

階層型データベース構造(列IDなどPARENT_ID)があり、行ごとに定義されており、最上位の行には。がありNULL PARENT_IDます。

このテーブルのすべての関係を別のテーブルにフラット化します。たとえば、祖父母、親、孫の1つの階層に3つのレコードがある場合、3つのレコードがあります。

**ANCESTOR, DESCENDANT**
grantparent, parent
grandparent, grandchild
parent, grandchild

(grandparent, grandchild)階層クエリを実行して孫が祖父母の子孫であると判断するのではなく、このフラット化されたテーブルにレコードが存在するかどうかを簡単に確認できます。

私の質問は、このフラット化されたテーブルを使用して、2つのノード間にあるすべてのレコードを最も効率的に返すにはどうすればよいかということです。例を使用して、パラメーターとして、grandparentおよびをパラメーターとして使用して、レコードgrandchildを取得するにはどうすればよいですか。(grandparent, parent)

これを解決するために階層クエリを使用したくありません...結合なしでこれを実行できるかどうか疑問に思っています。

4

3 に答える 3

2
SELECT  *
FROM    mytable
WHERE   descendant = @descendant
        AND hops < 
        (
        SELECT  hops
        FROM    mytable
        WHERE   descendant = @descendant
                AND ancestor = @ancestor
        )

これは、が実際にはの祖先@ancestorではない場合に自動的に処理されます。@descendant

これが高速に機能するように、インデックスを作成します(descendant, hops)

于 2010-11-03T18:42:08.123 に答える
1

試す:

select h1.descendant intermediate_node
from hierarchy h0 
join hierarchy h1 
  on h0.ancestor = h1.ancestor 
 and h0.hops > h1.hops  -- redundant condition, but may improve performance
join hierarchy h2
  on h1.ancestor = h2.ancestor 
 and h0.descendant = h2.descendant
where h0.ancestor = :ancestor and h0.descendant = :descendant
于 2010-11-03T18:33:32.450 に答える
0
SELECT
   distinct ancestor 
FROM 
   hierarchy 
WHERE descendant = :1 AND 
      ancestor IN (
                    SELECT 
                       distinct descendant 
                    FROM 
                       hierarchy WHERE ancestor = :2
                  )
于 2010-11-03T19:47:35.810 に答える