2

次の表から、user_id 53 (親と子) に関連するすべてのアイテムを選択したいと考えています。1、2、4、8、9 である必要があります。

my_table
--------------------------------------------
id    parent_id   user_id   sequence   depth
--------------------------------------------
1     null        50        1          1
2     1           52        1.2        2
3     1           52        1.3        2
4     2           53        1.2.4      3
5     2           52        1.2.5      3
6     3           52        1.3.6      3
7     3           51        1.3.7      3
8     4           51        1.2.4.8    4
9     4           51        1.2.4.9    4

CTE を使用すると、すべての子または親を選択できましたが、1 つのクエリだけで子と親を選択することはできませんでした。以下は、私が子を選択するために使用している cte です。

アイテムと子

with cte as (
    select t.id, t.parent_id, t.user_id 
    from my_table t 
    where t.user_id=53

    union all

    select t.id, t.parent_id, t.user_id 
    from my_table t
    inner join cte c on (c.parent_id=t.id)
)
select t.* from cte t;

アイテムと親

with cte as (
    select t.id, t.parent_id, t.user_id 
    from my_table t 
    where t.user_id=53

    union all

    select t.id, t.parent_id, t.user_id 
    from my_table t
    inner join cte c on (c.id=t.parent_id)
)
select t.* from cte t;

ありがとう。

4

4 に答える 4

4

シーケンスがあると非常に便利です。親には、探しているものの最初のサブセットに一致するシーケンスがあります。同じことが子供たちにも当てはまりますが、逆です。

以下はあなたが望むものに近づきます:

select mt.*
from (select sequence from my_table where USER_ID = 53) theone join
     my_table mt
     on mt.sequence like theone.sequence+ '%' or
        theone.sequence like mt.sequence + '%'

ただし、たとえば、10マッチングには注意する必要があります。1したがって、必要に応じて期間を追加しましょう。

select mt.*
from (select sequence from my_table where USER_ID = 53) theone join
     my_table mt
     on mt.sequence like theone.sequence+ '.%' or
        theone.sequence like mt.sequence + '.%'
于 2013-03-04T14:17:43.820 に答える
0

ここでの問題は、再帰的な SELECT. DBMS は、このようなクエリ用に作成されていません。しかし、それはもちろん可能です。

SELECT t1.* FROM Table1 t1 WHERE user_id = 53

UNION ALL

SELECT t2.* FROM Table1 t1, Table1 t2
WHERE
  (t1.id = t2.parent_id OR t1.parent_id = t2.id) AND t1.user_id = 53

このクエリは、それぞれの第 1 度近親者を返します。

再帰的な SELECT については、こちらをご覧ください: Recursive select in SQL


ここでのクエリの解決策: http://sqlfiddle.com/#!6/e1542/10/0

with cte as (
    select t.id, t.parent_id, t.user_id 
    from Table1 t 
    where t.user_id=53
),

cte1 as (
    select t.id, t.parent_id, t.user_id 
    from cte t

    union all

    select t.id, t.parent_id, t.user_id 
    from Table1 t
    inner join cte1 c on (c.parent_id=t.id)
),

cte2 as (
    select t.id, t.parent_id, t.user_id 
    from cte t

    union all

    select t.id, t.parent_id, t.user_id 
    from Table1 t
    inner join cte2 c on (c.id=t.parent_id)
)

select t.* from cte1 t

UNION

select t.* from cte2 t
于 2013-03-04T12:26:54.840 に答える