sql - CTE - 获取父级
问题描述
我知道有很多关于 CTE 的问题,但我仍然不知道该怎么做。我有包含列的表消息:id 和 previousMessageId。如何获得 id = 957 的父级 - 它应该是:950。
table Messages
--------------
id | previousMessageId
957 | 956
956 | 950
950 | NULL
这是我的查询:
WITH previous AS
(
SELECT id
FROM Messages
WHERE id = 957
UNION ALL
SELECT cur.id
FROM Messages cur
INNER JOIN previous ON cur.previousMessageID = previous.id
)
SELECT * FROM previous
它给了我:
957
958
但结果应该是:950
解决方案
您可以尝试如下。
declare @table table(id int, previousMessageId int)
insert into @table select 957 , 956
insert into @table select 956 , 950
insert into @table select 950 , NULL
insert into @table select 999 , 998
insert into @table select 998 , 997
insert into @table select 997 , NULL
;WITH previous
AS (SELECT id,
previousmessageid
FROM @table
WHERE id = 957
UNION ALL
SELECT cur.id,
cur.previousmessageid
FROM @table cur
INNER JOIN previous
ON cur.id = previous.previousmessageid)
SELECT ID
FROM previous
WHERE previousmessageid IS NULL
在上面的示例中,对于 Id 957,您将获得 950,对于 Id 999,您将获得 997
推荐阅读
- java - 在 java 和 android studio 中创建和操作按钮数组
- windows - 将多个 ip 地址分配给单个 NIC
- java - 如何在数组中转换嵌套的 ArrayList?
- r - 计算尺寸为 25000 x 25000 In R 的矩阵的逆矩阵
- tableau-api - 从 tableau 服务器更改参数时自动更新提取的数据源
- angular - 标题中出现错误“访问控制允许来源”
- java - java - 返回带有开关盒的字符串
- php - 如何获取上传路径
- android - 如何使用 Navigation Comp 为 Fragment 启用 Backstack。库
- java - 如何使用java将https put请求发送到其主体中具有json内容的特定主机?