我有一个包含这些示例行的persons
表:
+----+-------+-----------+
| id | name | parent_id |
+----+-------+-----------+
| 1 | max | (null) |
| 2 | payne | 1 |
| 3 | mike | 1 |
| 4 | sara | 2 |
| 7 | walt | (null) |
+----+-------+-----------+
每个人只列出一次,具有唯一的ID
,但在parent_id
中可以为空值。有些child
共享相同的parent_id
。
我还有另一个存储人员信息的tickets
表
+----+---------+-----------+
| id | request | person_id |
+----+---------+-----------+
| 1 | 1 | 1 |
| 2 | 1 | 3 |
| 3 | 2 | 2 |
| 4 | 2 | 3 |
| 5 | 2 | 7 |
+----+---------+-----------+
基本上,每张票可以有多个人(每个请求)。在此表中,我不存储parent_id
,因为它可以从persons
表中检索。
现在,我尝试使用以下SQL语句
表示请求#2的persons
层次结构
with x(id,name,parent_id)
as
(
select
p.id,p.name,p.parent_id
from
tickets t left join persons p on t.person_id = p.id
where
t.request=2
and p.parent_id is null /* for all parents */
union all
select
c.id,c.name,c.parent_id
from
tickets j left join persons c on j.person_id = c.id
join x on x.id = c.parent_id
where
j.request=2
) select * from x
但我收到此错误消息:
SQL Server数据库错误:递归中不允许外部联接 递归公用表表达式'x'的一部分。
我做错了什么?
答案 0 :(得分:1)
在CTE中构建树,然后将tickets
表连接到树:
with person_tree (id, name, parent_id)
as
(
select p.id, p.name, p.parent_id
from persons p
where p.parent_id is null
union all
select c.id, c.name, c.parent_id
from persons c
join person_tree p on c.parent_id = p.id
)
select *
from tickets t
left join person_tree p on t.person_id = p.id
where t.request = 2;
SQLFiddle:http://sqlfiddle.com/#!6/004df/28