8

テーブルの構造の例を次に示します。

ID    Name     ParentID
-----------------------
1     Ancestor      NULL
2     GrandFather   1
3     GrandMother   1
4     Child         3

返されるクエリを作成しようとしています

ID     Name        Family
----------------------------
 1     Ancestor 
 2     GrandFather Ancestor
 3     GrandMother Ancestor
 4     Child       Ancestor^GrandMother

トリッキーな部分は、すべての行のファミリーを上から下に表示したいということです。

誰かが私を正しい方向に向けることができれば、それはありがたいです:)

EDIT :: これは実際のクエリですが、同じ考え方に従います。行でエラーを返します: marketparent.family + '^'+ t2.marketGroupName は、marketparent が見つからないためです。

WITH marketparent ( marketGroupID,parentGroupID, marketGroupName,family)
AS
(
SELECT marketGroupID,
       parentGroupID,
       marketGroupName,
       '' as family 
 FROM EVE.dbo.invMarketGroups
 WHERE parentGroupID IS NULL
UNION ALL

    SELECT t2.parentGroupID,
     t2.marketGroupID,
     t2.marketGroupName,
     marketparent.family + '^'+ t2.marketGroupName
     FROM EVE.dbo.invMarketGroups as t2
     INNER JOIN marketparent as mp
     ON mp.marketGroupID = t2.parentGroupID
)

-- Statement using the CTE

SELECT TOP 10 *
FROM marketparent;
4

3 に答える 3

8

DBMS を指定しなかったため、PostgreSQL を想定しています

WITH RECURSIVE fam_tree (id, name, parent, family) as 
(
  SELECT id, 
         name, 
         parentid, 
         ''::text as family
  FROM the_unknown_table
  WHERE parent IS NULL

  UNION ALL

  SELECT t2.id, 
         t2.name, 
         t2.parentid, 
         fam_tree.family || '^' || t2.name
  FROM the_unknown_table t2 
     INNER JOIN fam_tree ON fam_tree.id = t2.parentid
)
SELECT *
FROM fam_tree;

これは標準 SQL (::text型キャストを除く) であり、ほとんどの最新の DBMS でほとんど変更を加えずに動作するはずです。

編集

SQL Server の場合、標準の連結文字を Microsoft の非標準文字に置き換える必要があり+ます (また、標準で必要とされているキーワードを削除する必要がありますrecursiveが、何らかの奇妙な理由で SQL Server によって拒否されます)。

WITH fam_tree (id, name, parent, family) as 
(
  SELECT id, 
         name, 
         parentid, 
         '' as family
  FROM the_unknown_table
  WHERE parent IS NULL

  UNION ALL

  SELECT t2.id, 
         t2.name, 
         t2.parentid, 
         fam_tree.family + '^' + t2.name
  FROM the_unknown_table t2 
     INNER JOIN fam_tree ON fam_tree.id = t2.parentid
)
SELECT *
FROM fam_tree;
于 2012-04-16T15:13:02.350 に答える
0
select T.ID, T.Name, (select name from table where ID=T.ParentID)as Family
from table T
于 2012-04-16T15:18:27.880 に答える
0

再帰的なCommon Table Expressionを使用できます。

declare @T table
(
  ID int,
  Name nvarchar(15),
  ParentID int
);

insert into @T values
(1,     N'Ancestor',      NULL),
(2,     N'GrandFather',   1),
(3,     N'GrandMother',   1),
(4,     N'Child',         3);

with C as
(
  select T.ID,
         T.Name,
         T.ParentID,
         cast(N' ' as nvarchar(max)) as Family
  from @T as T
  where T.ParentID is null
  union all
  select T.ID,
         T.Name,
         T.ParentID,
         C.Family+'^'+C.Name
  from @T as T
    inner join C
      on T.ParentID = C.ID
)
select C.ID,
       C.Name,
       stuff(C.Family, 1, 2, '') as Family
from C;
于 2012-04-16T15:14:15.683 に答える