2011-08-02 10 views
0

単一のデータベーステーブル内のデータの階層を下から上にクエリしようとしています(特定の型の親を持たない親を含めたくない子供は当局のために)。次のようにスキーマおよびサンプルデータは、次のとおりです。Sql Server 2005を使用したボトムアップ再帰CTEのフィルタリング

create table Users(
id int, 
name varchar(100)); 

insert into Users values (1, 'Jill'); 

create table nodes(
    id int, 
    name varchar(100), 
    parent int, 
    nodetype int); 

insert into nodes values (1, 'A', 0, 1); 
insert into nodes values (2, 'B', 0, 1); 
insert into nodes values (3, 'C', 1, 1); 
insert into nodes values (4, 'D', 3, 2); 
insert into nodes values (5, 'E', 1, 1); 
insert into nodes values (6, 'F', 5, 2); 
insert into nodes values (7, 'G', 5, 2); 

create table nodeAccess(
    userid int, 
    nodeid int, 
    access int); 

insert into nodeAccess values (1, 1, 1); 
insert into nodeAccess values (1, 2, 1); 
insert into nodeAccess values (1, 3, 1); 
insert into nodeAccess values (1, 4, 1); 
insert into nodeAccess values (1, 5, 1); 
insert into nodeAccess values (1, 6, 0); 
insert into nodeAccess values (1, 7, 1); 


with Tree(id, name, nodetype, parent) 
as 
(
    select n.id, n.name, n.nodetype, n.parent 
    from nodes as n 
    inner join nodeAccess as na on na.nodeid = n.id 
    where na.access =1 and na.userid=1 and n.nodetype=2 

    union all 

    select n.id, n.name, n.nodetype, n.parent 
    from nodes as n 
    inner join Tree as t on t.parent = n.id 
    inner join nodeAccess as na on na.nodeid = n.id 
    where na.access =1 and na.userid=1 and n.nodetype=1 
) 
select * from Tree 

収量:

id name nodetype parent 
    4 D  2    3 
    7 G  2    5 
    5 E  1    1 
    1 A  1    0 
    3 C  1    1 
    1 A  1    0 

どのように私は結果セットの重複を含めることはできませんか?実表に対する照会には、より多くのノードが最低レベルにあり、したがって親ノードの複製がさらに多くなります。ソリューションは少なくともSQL Server 2005で動作する必要があります。

ありがとうございます!

答えて

0

最も簡単な(必ずしも最も効率的な)解決策:

... 
) 
SELECT DISTINCT id,name,nodetype,parent FROM Tree; 

DISTINCTオペレータは、ソートを実装しているためこれはあなたのサンプル出力からの順序を変更。意図的な注文がある場合はそれを検出できませんが、ご希望の注文がある場合はORDER BYを追加することができます。

関連する問題