2015-05-04 18 views
0

編輯:SQL Fiddle here如何表示無用的子父行?

我有一個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'.

什麼錯誤,我在幹嘛?

+3

只建立與'tickets'內的CTE再加入'人員的層次結構'在外部選擇表(到'x''表「) –

+1

@a_horse_with_no_name我需要'個人'表,因爲它包含'parent_id'信息。請問您能詳細說明一下嗎? – Ahmad

+0

對不起。那麼當然你需要用'persons'表構建層次結構,並將'tickets'錶鏈接到外部選擇。 –

回答

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

相關問題