1

我使用SQL 2005,與數以百萬計的記錄現有數據(所以數據結構不能改變),我試圖做到以下幾點:充分利用自參照表分層數據在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 

我已經看到了關於這個其他各種問題,但不能看到的答案,我問題。 nearset的東西是oracle'通過事先連接',如果我使用的是oracle dB,那將會很棒!有任何想法嗎?

乾杯, 傑森

+0

我認爲這是同一個問題http://stackoverflow.com/questions/539155/ordering-hierarchy-from-recursive-query-results-in-sql-2005是相同的問題。 – gjvdkamp 2011-03-31 10:03:47

+0

是的,你是對的 - 感謝這個評論我找到了我的答案(下面!) – Jay 2011-03-31 11:52:20

回答

0

我想我已經找到這是我要加入錨固構件上,而不是在車間桌子答案。感謝gjvdkamp這個類似的帖子,這讓我重新評估了錯誤的'真實'sql語句。