0
我有一個persons
表包含這些樣本行:
+----+-------+-----------+
| id | name | parent_id |
+----+-------+-----------+
| 1 | max | (null) |
| 2 | payne | 1 |
| 3 | mike | 1 |
| 4 | sara | 2 |
| 7 | walt | (null) |
+----+-------+-----------+
每個人只列出一次,以獨特的ID
但可以在parent_id
空值。一些child
s共享parent_id
。
我還具有存儲人物信息
+----+---------+-----------+
| id | request | person_id |
+----+---------+-----------+
| 1 | 1 | 1 |
| 2 | 1 | 3 |
| 3 | 2 | 2 |
| 4 | 2 | 3 |
| 5 | 2 | 7 |
+----+---------+-----------+
基本上另一個tickets
表,每張票可以有多個的人(每個請求)。在此表中,我不存儲parent_id
,因爲它可以從persons
表中檢索。
現在我試着用下面的SQL語句
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
代表persons
層次的要求#2,但我收到此錯誤信息:
SQL Server Database Error: Outer join is not allowed in the recursive part of a recursive common table expression 'x'.
什麼錯誤,我在幹嘛?
只建立與'tickets'內的CTE再加入'人員的層次結構'在外部選擇表(到'x''表「) –
@a_horse_with_no_name我需要'個人'表,因爲它包含'parent_id'信息。請問您能詳細說明一下嗎? – Ahmad
對不起。那麼當然你需要用'persons'表構建層次結構,並將'tickets'錶鏈接到外部選擇。 –