过滤SQL树查询

时间:2011-10-04 21:50:52

标签: sql filter tree

如果我有一个如下所示的树查询,我想过滤Name ='Son'并选择其所有父记录,因此结果应该产生前3行。我将如何构建我的查询?我已经读过我应该使用Common Table Expression(CTE),但我是CTE的新手。谁能帮我?感谢。

select 1 AS id, NULL AS parent, 'God' AS name
    UNION 
    select 2 AS id, 1 AS parent, 'Father' AS name
    UNION 
    select 3 AS id, 2 AS parent, 'Son' AS name
    UNION 
    select 4 AS id, NULL AS parent, 'Godmother' AS name
    UNION 
    select 5 AS id, 4 AS parent, 'Mother' AS name

2 个答案:

答案 0 :(得分:1)

听起来您可以将树存储在表中(或使用上面的SQL定义视图),然后如果您使用的是Oracle,则可以使用CONNECT BY函数来过滤记录。

答案 1 :(得分:0)

这是你要找的吗?

;with SomeCTE as
(
select *
from (
select 1 AS id, NULL AS parent, 'God' AS name     
UNION      
select 2 AS id, 1 AS parent, 'Father' AS name     
UNION      
select 3 AS id, 2 AS parent, 'Son' AS name     
UNION      
select 4 AS id, NULL AS parent, 'Godmother' AS name    
UNION      
select 5 AS id, 4 AS parent, 'Mother' AS name ) as a
)
select *
from SomeCTE a
left join SomeCTE b
on a.parent = b.id
left join SomeCTE c
on b.parent = c.id
where a.name = 'son'