私はSQL 2005を使用しており、数百万のレコードの既存のデータを使用しています(データ構造を変更することはできません)。次のことをしようとしています:
自己参照テーブルにいくつかのデータがあります (次の例は別の質問からのもので、達成しようとしていることを示すために少し変更されています)。次の形式で結果のツリーを引き出す必要があります。
Parent
Child1 of Parent
Child1 of Child 1
Child2 of Child 1
Child2 of Parent
Child1 of Child 2
私の実際のデータは 9 レベルの深さになり、CTE を使用して結果を取得しようとしました。ただし、これにより次が生成されます。
Parent
Child1 of Parent
Child2 of Parent
Child1 of Child 1
Child2 of Child 1
Child1 of Child 2
以下は、私が使用しているクエリの例です。
create table workshop (
w_id smallint primary key,
p_id smallint,
s_date smalldatetime,
title varchar(100))
go
alter table workshop add constraint fk_wkshp foreign key (p_id)
references workshop(w_id)
go
insert into workshop (w_id, p_id, s_date, title) values (1, null,
'5/2/2007', 'Parent')
insert into workshop (w_id, p_id, s_date, title) values (2, 1,
'5/3/2007', 'Child 1 of the parent')
insert into workshop (w_id, p_id, s_date, title) values (3, 1,
'5/5/2007', 'Child 2 of the parent')
insert into workshop (w_id, p_id, s_date, title) values (4, 2,
'5/4/2007', 'Child of Child 1')
insert into workshop (w_id, p_id, s_date, title) values (5, 2,
'5/5/2007', 'Child 2 of the child of the parent')
insert into workshop (w_id, p_id, s_date, title) values (6, 3,
'5/7/2007', 'Child of the child 2')
insert into workshop (w_id, p_id, s_date, title) values (7, null,
'5/7/2007', '2nd Parent')
insert into workshop (w_id, p_id, s_date, title) values (8, 7,
'5/7/2007', 'Child of 2nd Parent')
insert into workshop (w_id, p_id, s_date, title) values (9, 7,
'5/7/2007', 'Child of 2nd Parent')
go
declare @id smallint
set @id = 1
;with events (w_id, p_id, s_date, title)
as
(
-- the anchor member
select
w_id, p_id, s_date, title
from
workshop
where w_id = @id
-- the recursive member
union all
select
w.w_id, w.p_id, w.s_date, w.title
from
workshop w
-- the key is to join to the CTE
join events e on e.w_id = w.p_id
)
select * from events
drop table workshop
go
これに関連する他のさまざまな質問を見てきましたが、私の問題に対する答えが見つかりません。最も近いのは、オラクルの「事前に接続」です。これは、オラクル dB を使用している場合に最適です。何か案は?
乾杯、ジェイソン