获取历史记录
- 作者: 硕大的菊花向阳开
- 来源: 51数据库
- 2022-12-01
问题描述
我有一个包含 RequestId 和 OldRequestId 两列的表格.
I have the table with the two columns RequestId and OldRequestId.
如果我传递一个 RequestId,它应该检索我的特定记录.
If I pass a RequestId, it should retrieve me the specific record.
如果检索到的记录中 OldRequestId 不为空,它也应该带上旧的请求数据.
If the OldRequestId is not null in the retrieved record, it should bring the old request data as well.
它应该一直持续到 OldRequestId 为空.
It should go on until the OldRequestId is null.
有人可以帮我为这个需求写出最好的 SQL 查询吗?
Can someone help me to write the best possible SQL query for this requirement?
推荐答案
您可以使用递归公用表表达式 (CTE) 解决此问题:
You can solve this using a recursive Common Table Expression (CTE):
DECLARE
@RequestID int = 6;
WITH
ReqCTE AS
(
SELECT
RequestID,
OldRequestID
FROM
Requests
WHERE
RequestID = @RequestID
UNION ALL SELECT
R.RequestID,
R.OldRequestID
FROM
ReqCTE C
INNER JOIN Requests R
ON R.RequestID = C.OldRequestID
)
SELECT
*
FROM
ReqCTE;
推荐阅读
热点文章
检查拆分键盘
0
带有“上一个"的工具栏和“下一个"用于键盘输入AccessoryView
0
Activity 启动时显示软键盘
0
UIWebView 键盘 - 摆脱“上一个/下一个/完成"酒吧
0
在 iOS7 中边缘滑动时,使键盘与 UIView 同步动画
0
我的 iOS 应用程序中的键盘在 iPhone 6 上太高了.如何在 XCode 中调整键盘的分辨率?
0
android:inputType="textEmailAddress";- '@' 键和 '.com' 键?
0
禁用 iPhone 中键盘的方向
0
Android 2.3 模拟器上的印地语键盘问题
0
keyDown 没有被调用
0
