首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将递归CTE与另一个查询组合

将递归CTE与另一个查询组合
EN

Stack Overflow用户
提问于 2020-10-01 19:01:15
回答 1查看 56关注 0票数 0

我有一个位置表,每个位置都可以有一个父位置

代码语言:javascript
复制
LocationId | ParentLocationId
-----------------------------
     1              null
     2                1
     3                2
     4                2

我设法创建了一个递归CTE,它为任何给定的位置id提供父位置id (加上原始位置id

代码语言:javascript
复制
WITH       GetLocationParents AS
  (
    select    [LocationId],    [ParentLocationId]   from    Locations
    where     LocationId = 3
    UNION ALL 
    select    i.[LocationId],    i.[ParentLocationId]
    from        Locations i 
    join  GetLocationParents cte on cte.ParentLocationId = i.LocationId
  )
SELECT  [ParentLocationId] FROM GetLocationParents
WHERE   [ParentLocationId] is not NULL;

例如,where LocationId = 3将返回:

代码语言:javascript
复制
ParentLocationId
----------------
       3
       2
       1

在另一个表中,我有一个查询,它将返回LocationId作为其中一个字段:

代码语言:javascript
复制
select exi.PersonId, exi.LocationId from Persons e
left join PersonHasLocations exi on e.PersonId = exi.PersonId
left join Locations i on exi.LocationId = i.LocationId

如果使用where子句,它将返回如下内容:

代码语言:javascript
复制
PersonId | LocationId
---------------------
    100          3

我尝试将这些查询组合在一起以获得结果:

代码语言:javascript
复制
PersonId | LocationId
---------------------
   100        3
   100        2
   100        1

我尝试执行以下命令,但仍然只返回第一行:

代码语言:javascript
复制
WITH
    GetLocationParents AS
        (select    [LocationId],    [ParentLocationId]   from    Locations
        --where LocationId = 3
        UNION ALL 
        select    i.[LocationId],    i.[ParentLocationId]
        from    Locations i    inner join GetLocationParents cte 
        on cte.ParentLocationId = i.LocationId),
    GetPersons AS
        (select exi.PersonId, exi.LocationID from Persons e
        left join PersonHasLocations exi on e.PersonID = exi.PersonId
        left join Locations i on exi.LocationId = i.LocationID)
SELECT * FROM GetLocationParents gip
INNER JOIN GetPersons ge on ge.LocationId = gip.LocationID
WHERE ge.PersonId = 100

像这样将递归查询与普通查询合并是可能的吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-01 19:38:30

我猜你的cte里有个小bug。我建议将查询更改如下:

代码语言:javascript
复制
DECLARE @t TABLE (
  LocationId int,
  ParentLocationId int
)

INSERT INTO @t VALUES
    (1, NULL)
   ,(2, 1)
   ,(3, 2)
   ,(4, 2)

;WITH       GetLocationParents AS
  (
    select    [LocationId] AS k, [LocationId],    [ParentLocationId]   from    @t
    UNION ALL 
    select    k, i.[LocationId],    i.[ParentLocationId]
    from        GetLocationParents cte
    join @t i   on cte.ParentLocationId = i.LocationId
  )
SELECT  *
 FROM GetLocationParents
 WHERE k = 3

这样,您就会收到一个列表,在第一列中包含您筛选的值,在第二列中包含该值以上的所有依赖“级别”。然后可以使用它来连接到您的第二个表。

请记住,根据您的级别数量,您必须注意MAX RECUSRSION

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64154010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档