1

次のスキーマとデータがあり、クロージャー テーブル パターンを使用している場合:

+----+----------+------------+--------+ | id | ancestor | descendant | length | +----+----------+------------+--------+ | 1 | 2 | 2 | 0 | | 2 | 2 | 12 | 1 | | 3 | 2 | 13 | 1 | | 4 | 2 | 14 | 1 | | 5 | 2 | 15 | 1 | | 10 | 12 | 12 | 0 | | 11 | 13 | 13 | 0 | | 12 | 14 | 14 | 0 | | 13 | 15 | 15 | 0 | | 9 | 17 | 20 | 1 | | 8 | 17 | 19 | 1 | | 7 | 17 | 18 | 1 | | 6 | 17 | 17 | 0 | | 14 | 18 | 18 | 0 | | 15 | 19 | 19 | 0 | | 16 | 20 | 20 | 0 | +----+----------+------------+--------+

行 id のすべての兄弟行を取得するために、メイン テーブルに戻る結合クエリはどのようになります2か?

+----+----------+------------+--------+ | id | ancestor | descendant | length | +----+----------+------------+--------+ | 3 | 2 | 13 | 1 | | 4 | 2 | 14 | 1 | | 5 | 2 | 15 | 1 | +----+----------+------------+--------+

4

1 に答える 1

2

特定のノードの兄弟は、同じ祖先を持つことになります。ただし、これには「1」とリストが含まれます。

select t.*
from table t 
where t.ancestor = (select ancestor from table t2 where t.id = 2);

ancestorあなたの表では、 が と同じであることが何を意味するのかわかりませんdescendant。しかし、次のクエリが必要だと思います。

select t.*
from table t 
where t.ancestor = (select ancestor from table t2 where t2.id = 2) and
      t.ancestor <> t.descendant and
      t.id <> 2;

編集:

これは、次のような明示的な結合として実行できます。

select t.*
from table t join
     table t2
     on t.ancestor = t2.ancestor and
        t2.id = 2 a
where t.id <> 2 and
      t.ancestor <> t.descendant;

注: t.id <> 2「2」はそれ自体の兄弟とは見なされないように、条件も追加しました。

于 2014-03-02T02:42:39.363 に答える