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

棘手的部分是我想以自上而下的顺序显示所有行的系列。

如果有人能指出我正确的方向,将不胜感激:)

编辑 :: 这是真正的查询,但它遵循相同的想法。它在线返回错误: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

您可以使用递归公用表表达式

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 回答
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 回答