我需要一些关于SQL代码的帮助。我有2个表,第一个是表名
NameID Name
1 John
2 Paul
3 Jessica
4 Nancy
5 Sam
6 Jane
7 Jimmy
第二个是表Family
FamilyID NameID ChildID
1 1 2
2 1 3
3 2 4
4 3 5
5 3 6
6 5 7
字段" NameID"和#34; ChildID"在表中,Family连接到字段" NameID"在表名称中。所以,如果我把它放在一棵树上就会像这样
John
/ \
Paul Jessica
/ / \
Nancy Sam Jane
/
Jimmy
我需要的是能够找到" All"的SQL代码。父母一定记录。例如:
我想知道吉米的所有父母,结果将是:山姆, 杰西卡,约翰
我想了解南希的所有家长,结果将是:保罗,约翰
答案 0 :(得分:4)
在这里,使用递归CTE如下:
DECLARE @pName VARCHAR(20)
SET @pName = 'Jane'
;WITH RecursiveFamilyCTE
AS (
SELECT
ParentName.NAME,
ParentName.NameID,
f.ChildID
FROM
dbo.Family AS f
JOIN NAME AS ChildName
ON f.ChildID = ChildName.NameID
JOIN Name AS ParentName
ON f.NameID = ParentName.NameID
WHERE
ChildName.NAME = @pName
UNION ALL
SELECT
ParentName.NAME,
ParentName.NameID,
f.ChildID
FROM
dbo.Family AS f
JOIN NAME AS ChildName
ON f.ChildID = ChildName.NameID
JOIN Name AS ParentName
ON f.NameID = ParentName.NameID
JOIN RecursiveFamilyCTE
ON f.ChildID = RecursiveFamilyCTE.NameID
)
SELECT
NAME
FROM
RecursiveFamilyCTE
答案 1 :(得分:0)
递归查询是继续查询的方法。下面是一个灵活的查询,您可以在没有参数的情况下运行。
with familytree as (
select childid, nameid
from family
where nameid is not null
union all
select f.childid, t.nameid
from familytree t
inner join family f on t.childid = f.nameid
),
treedetails as (
select
p.nameid as parentid, p.name as parent,
c.nameid as childid, c.name as child
from familytree a
left join name p on a.nameid = p.nameid
left join name c on a.childid = c.nameid
)
-- uncomment the query of your choice
-- select * from treedetails where child = 'Jimmy'
-- select * from treedetails where child = 'Jane'
-- select * from treedetails where child = 'Nancy'
--
-- show me children and grandchildren of Jessica
-- select * from treedetails where parent = 'Jessica'