Sql 具有2个并集的公用表表达式计数器
如果我对一个有母亲和父亲的家庭有一个通用的表表达式,我如何增加“世代”计数器?一个家庭应该将孩子作为第0代,父母作为第1代,四位祖父母作为第2代。但是循环执行两次,每组祖父母执行一次Sql 具有2个并集的公用表表达式计数器,sql,sql-server,tsql,recursion,common-table-expression,Sql,Sql Server,Tsql,Recursion,Common Table Expression,如果我对一个有母亲和父亲的家庭有一个通用的表表达式,我如何增加“世代”计数器?一个家庭应该将孩子作为第0代,父母作为第1代,四位祖父母作为第2代。但是循环执行两次,每组祖父母执行一次 ;WITH FamilyTree AS ( SELECT *, 0 AS Generation FROM myTable WHERE [id] = 99 UNION ALL SELECT name, Generation + 1 FROM myTable AS Fa
;WITH FamilyTree
AS
(
SELECT *, 0 AS Generation
FROM myTable
WHERE [id] = 99
UNION ALL
SELECT name, Generation + 1
FROM myTable AS Fam
INNER JOIN FamilyTree
ON Fam.[id] = FamilyTree.[motherid]
UNION ALL
SELECT name, Generation + 1
FROM myTable AS Fam
INNER JOIN FamilyTree
ON Fam.[id] = FamilyTree.[fatherid]
)
SELECT generation, name FROM FamilyTree
在一次过的一个代沟中更改连接查看亲属,而不是在CTE中使用2个递归子句。这两个子句构成了一个部分交叉联接,这就是为什么会有额外的行
;WITH FamilyTree
AS
(
SELECT *, 0 AS Generation
FROM myTable
WHERE [id] = 99
UNION ALL
SELECT name, Generation + 1
FROM myTable AS Fam
INNER JOIN FamilyTree
ON Fam.[id] IN (FamilyTree.[motherid], FamilyTree.[fatherid])
)
SELECT generation, name FROM FamilyTree