我的数据库中有一个用户表,其中包含两个字段
我正在尝试构造一个查询,以列出与分层结构中的user_id关联的所有manager_id。
因此,如果我提供一个user_id,我将得到该用户管理员,然后是该人员管理员,一直到最顶端。
到目前为止,我已经尝试过了,但是没有给出我所需要的:
WITH cte(user_id, manager_id) as (
SELECT user_id, manager_id
FROM user
WHERE manager_id=@userid
UNION ALL
SELECT u.user_id, u.manager_id,
FROM user u
INNER JOIN cte c on e.manager_id = c.employee_id
)
INSERT INTO #tbl (manager_id)
select user_id, manager_id from cte;
如果有人能指出我正确的方向,那就太好了。
我考虑过While循环,但这可能效率不高,而且我不太确定如何实现该循环。
答案 0 :(得分:0)
摆脱CTE声明中的此列列表,该列表与您实际上在CTE中选择的列无关:
WITH cte(employee_id, name, reports_to_emp_no, job_number) as (
只要做到这一点:
WITH cte as (
答案 1 :(得分:0)
OP请求while循环,而while(ha,pun)这可能不是最好的方法。 (:
这是我创建的示例数据(以后请提供):
CREATE TABLE #temp (userID int, managerID int)
INSERT INTO #temp VALUES (1, 3)
INSERT INTO #temp VALUES (2, 3)
INSERT INTO #temp VALUES (3, 7)
INSERT INTO #temp VALUES (4, 6)
INSERT INTO #temp VALUES (5, 7)
INSERT INTO #temp VALUES (6, 9)
INSERT INTO #temp VALUES (7, 10)
INSERT INTO #temp VALUES (8, 10)
INSERT INTO #temp VALUES (9, 10)
INSERT INTO #temp VALUES (10, 12)
INSERT INTO #temp VALUES (11, 12)
INSERT INTO #temp VALUES (12, NULL)
循环时
CREATE TABLE #results (userID INT, managerID INT)
DECLARE @currentUser INT = 1 -- Would be your parameter!
DECLARE @maxUser INT
DECLARE @userManager INT
SELECT @maxUser = MAX(userID) FROM #temp
WHILE @currentUser <= @maxUser
BEGIN
SELECT @userManager = managerID FROM #temp WHERE userID = @currentUser
INSERT INTO #results VALUES (@currentUser, @userManager)
SET @currentUser = @userManager
END
SELECT * FROM #results
DROP TABLE #temp
DROP TABLE #results
答案 2 :(得分:0)
我建议递归解决方案:
WITH Parent AS
(
SELECT * FROM user WHERE user_id=@userId
UNION ALL
SELECT T.* FROM user T
JOIN Parent P ON P.manager_id=T.user_id
)
SELECT * FROM Parent
要查看演示,请运行以下命令:
SELECT * INTO #t FROM (VALUES (1,NULL),(2,1),(3,2),(4,1)) T(user_id,manager_id);
DECLARE @userId int = 3;
WITH Parent AS
(
SELECT * FROM #t WHERE user_id=@userId
UNION ALL
SELECT T.* FROM #t T
JOIN Parent P ON P.manager_id=T.user_id
)
SELECT * FROM Parent