質問

階層データベースStrucutre、例えば列があります IDPARENT_ID 各行に対して定義されており、上部レベルの行に NULL PARENT_ID.

私はこのテーブルからすべての関係を別のテーブルに平らにしています。

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

階層的なクエリを実行して孫が祖父母の子孫であると判断するのではなく、 (grandparent, grandchild) この平らなテーブルに記録します。

私の質問は、この平らなテーブルを使用して、2つのノードの間のすべてのレコードを最も効率的に返すにはどうすればよいですか。例を使用して grandparentgrandchild 私のパラメーターとして、どうすれば戻すことができますか (grandparent, parent) 記録。

私はこれを解決するために階層クエリを使用したくありません...私は参加せずにこれを行うことができるかどうか疑問に思っています。

役に立ちましたか?

解決

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

これは、自動的にケースの処理を行います @ancestor 実際にはそうではありません @descendant祖先。

でインデックスを作成します (descendant, hops) これが速く動作するため。

他のヒント

試す:

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
SELECT
   distinct ancestor 
FROM 
   hierarchy 
WHERE descendant = :1 AND 
      ancestor IN (
                    SELECT 
                       distinct descendant 
                    FROM 
                       hierarchy WHERE ancestor = :2
                  )
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top