sql - 在sql中选择父子案例的递归查询
问题描述
我正在尝试使用公用表表达式对查询实现递归。但是我对它不是很熟悉。该场景围绕在父案例和子案例之间,其中家长在登录时可以看到他自己的案例以及他所有的孩子案例等等。但是我无法使用 cte 表达式来做到这一点。
我有一个用户表和一个包含主要和次要用户的关系表。主要用户是父母,次要用户是孩子。
以下是我的查询。
select *
from dbo.[Case] c
left join dbo.[User] u on c.AssignedTo = u.UserId
left join dbo.[User] uu on c.AssignedTo = uu.UserId
where uu.UserId in (select SecondaryUser from dbo.[Relations]
where PrimaryUser = 'f422233f-9c70-4052-81a5-e2525707df0b')
or u.UserId = 'f422233f-9c70-4052-81a5-e2525707df0b'
但是上面的查询只返回一个父母和一个孩子的情况。而且我希望有多个父母和他们的多个孩子使用公用表表达式。
假设部分用户如下
Id Name Email
001 Salar salar@gmail.com
002 Ather ather@gmail.com
003 John john@gmail.com
并在关系表中
Id PrimaryUser SecondaryUser
101 001 002
001 002 003
以及他们的指定案例
Id CaseTitle CaseDescription AssingedTo
101 Case 1 First case 001
102 Case 2 Second case 002
103 Case 3 Third case 003
因此,当我登录到 001 id 时,我应该看到所有三个案例,当我使用 002 登录时,我应该看到最后两个案例。
解决方案
此查询将返回与第一个 ID 相关的所有用户 ID。您可以将结果与案例结合起来:
declare @Users as table
(UserId int)
;
declare @Relations as table
(PrimaryUser int, SecondaryUser int)
;
INSERT INTO @Relations
(PrimaryUser, SecondaryUser)
VALUES
(1,2),
(1,3),
(2,4),
(2,7),
(2,8),
(5,6),
(6,19)
INSERT INTO @Users
(UserId)
VALUES
(1),
(2),
(3),
(4),
(5),
(7),
(5),
(6),
(19),
(20)
;WITH cte1 AS (
SELECT UserId AS [User]
FROM @Users
WHERE UserId = 5
GROUP BY UserId
UNION ALL
SELECT SecondaryUser AS [User]
FROM cte1
JOIN @Relations t
ON t.PrimaryUser = cte1.[User]
)
SELECT [User] FROM cte1
推荐阅读
- python - Python:将绑定方法更改为另一种方法
- javascript - Javascript VS Objective-C VS Swift 中的经典继承与原型继承
- npm - npm 错误!在“...”附近解析时 JSON 输入意外结束:{“shasum”:“ae6c2edf”
- android - 如何解决工作管理器的多实例问题?
- laravel - React-Native TypeError: Undefined is not an object (评估 this.state.signatures.length)
- reactjs - 使用 ReactJS -> Express 还是使用 Express -> ReactJS 更好?
- python - Keras 给中间层输入,得到最终输出
- sql-server - SQL Server 可以自己执行基于哈希的行相等(用于 MERGE 操作)吗?
- javascript - 无法使用带有 webpack 和 ES6 设置的 document.getElementById('password').addEventListener() 调用函数
- postgresql-9.6 - 读取表时,出现错误:无法访问文件“$libdir/postgis-2.3”:没有这样的文件或目录