【问题标题】:SQL Server query to get nested child records based on id provided by userSQL Server 查询以根据用户提供的 id 获取嵌套的子记录
【发布时间】:2021-12-22 18:28:37
【问题描述】:

我有以下格式的 SQL Server 数据:

在上表中,parentid 和 sourceid 是相关的,就像父子关系一样。

在第一行 parentid 'A' 是第二行的 sourceid。用户将提供 sourceid 的输入,并基于该 sourceid,我需要获取其相关的子记录。

例如,如果用户提供输入源 id 为 'A1',则输出应如下所示:

我尝试使用自连接,但无法在表中获取相关子记录。

select * 
from testrecords1 t1
join testrecords1 t2 on t1.parentid = t2.sourceid
where t1.sourceid = 'A1'

此查询仅产生一条记录。请提供更正/建议以实现所需的输出。

【问题讨论】:

    标签: sql-server join parent-child common-table-expression self-join


    【解决方案1】:

    您可以使用Common Table Expression (CTE) 进行递归查询。

    查询可以写成:

    ;with MyCTE 
    as
       (  
          SELECT Parentid, Sourceid from testrecords1 where SourceId = @SourceId
            UNION ALL  
          SELECT t1.Parentid, t1.Sourceid from testrecords1 t1
          inner join MyCTE t2 on t1.SourceId = t2.Parentid
        )  
     
    SELECT * FROM MyCTE 
    

    其中@SourceId是过滤器的参数。

    【讨论】:

      猜你喜欢
      • 2020-07-26
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多