代码之家  ›  专栏  ›  技术社区  ›  Omu

查询自身带有FK的层次结构、树、表

  •  1
  • Omu  · 技术社区  · 15 年前

    我有这张桌子

    Id PId      Name   Value
    ------------------------
    1  null     foo     null
    2  1        bar     null
    3  2        foobar  hi
    4  1        bar1    hey
    

    我需要一个能给出这个结果的查询:

    Name           | Value
    -----------------------
    foo bar foobar | hi
    foo bar1       | hey
    
    1 回复  |  直到 15 年前
        1
  •  0
  •   Omu    15 年前
    with s( id, pid, name, value) as
    (
    select f.id, f.pid, cast(f.name as nvarchar) as name, f.value from foos f 
    where f.pid is null
    union all
    select f.id, f.pid, cast(s.name + f.name as nvarchar) as name, f.value from foos f inner join s on f.pid = s.id
    )
    select * from s
    where not exists(select * from foos where pid = s.id)
    
    推荐文章