SQL-如何通过ID获取祖父母、父母、孩子的树状视图
我有两个表,其中Customer表有Customer数据,relations表有Customer的关系SQL-如何通过ID获取祖父母、父母、孩子的树状视图,sql,sql-server,Sql,Sql Server,我有两个表,其中Customer表有Customer数据,relations表有Customer的关系 CREATE Table Customer ( id int, name nvarchar(10) ) INSERT INTO Customer Values (1, 'aaa'), (2, 'bbb'), (3, 'ccc'), (4, 'ddd'), (5, 'eee'), (6, 'fff'), (7, 'ggg'), (8, '
CREATE Table Customer
(
id int,
name nvarchar(10)
)
INSERT INTO Customer Values
(1, 'aaa'),
(2, 'bbb'),
(3, 'ccc'),
(4, 'ddd'),
(5, 'eee'),
(6, 'fff'),
(7, 'ggg'),
(8, 'hhh'),
(9, 'iii'),
(10, 'jjj'),
(11, 'kkk'),
(12, 'lll')
CREATE TABLE Relations
(
id int,
parentid int
)
INSERT INTO Relations VALUES
(2, 1),
(3, 1),
(4, 2),
(5, 2),
(6, 1),
(7, 4),
(8, 5),
(9, 8),
(10, 8),
(12, 7)
我想按ID查找祖父母、父母和孩子。例如:如果我想查找ID=4的所有关系,我应该按以下格式得到结果。如果ID有父项或父项,则在顶部按父项排序。如果不是,则必须显示该ID的子项
祖父母| aaa
Parent|bbb
Child|ggg
Child|lll
请您在“SQL Server”中帮助我进行上述查询。您可以使用递归CTE(公共表表达式)获取此信息。例如,对于ID=4,您可以执行以下操作:
with
a as ( -- get ancestors
select 0 as lvl, id, name from customer where id = 4
union all
select a.lvl - 1, c.id, c.name
from a
join relations r on a.id = r.id
join customer c on c.id = r.parentid
),
d as ( -- get descendants
select 0 as lvl, id, name from customer where id = 4
union all
select d.lvl + 1, c.id, c.name
from d
join relations r on d.id = r.parentid
join customer c on c.id = r.id
)
select lvl, id, name from a
union
select lvl, id, name from d
order by lvl
结果:
lvl id name
--- -- ----
-2 1 aaa
-1 2 bbb
0 4 ddd
1 7 ggg
2 12 lll
你需要做一些调整来提升和降低你的层次结构。尝试更好地指定你的意思,例如,给定的示例,“4”将产生一些可能超出你的规范的内容:父级(1)>父级(2)>你的节点(4)>节点的子级(7)。可能重复