SQL开发知识:SQL Server 通过with as方法查询树型结构

什么是树型结构?

树型结构是一种用于描述层次关系的非循环有向图结构。将根节点看作第0层,第1层为其子节点层,第2层为子节点的子节点层,以此类推。

为什么需要查询树型结构?

查询树型结构可以非常方便地获取一个节点的所有子节点、父节点和祖先节点。这在数据分析和决策中经常用到。

如何用with as方法查询树型结构?

在SQL Server中,可以使用with as方法实现查询树型结构。

1. 创建数据库表格

使用以下代码创建一个测试用的员工表格:

CREATE TABLE Employees (

EmployeeID INT PRIMARY KEY,

EmployeeName VARCHAR(20) NOT NULL,

ManagerID INT NULL

);

INSERT INTO Employees (EmployeeID, EmployeeName, ManagerID) VALUES

(1, 'Alice', NULL),

(2, 'Bob', 1),

(3, 'Charlie', 2),

(4, 'David', 2),

(5, 'Eve', 1),

(6, 'Frank', 5),

(7, 'Grace', 5),

(8, 'Henry', 6);

2. 使用with as方法查询树型结构

使用以下代码查询Alice的所有下属:

WITH EmployeeHierarchy (EmployeeID, EmployeeName, ManagerID, HierarchyLevel)

AS

(

-- Anchor member definition

SELECT EmployeeID, EmployeeName, ManagerID, 0 AS HierarchyLevel

FROM Employees

WHERE EmployeeID = 1

UNION ALL

-- Recursive member definition

SELECT e.EmployeeID, e.EmployeeName, e.ManagerID, eh.HierarchyLevel + 1

FROM EmployeeHierarchy AS eh

JOIN Employees AS e

ON eh.EmployeeID = e.ManagerID

)

SELECT *

FROM EmployeeHierarchy;

输出结果如下:

EmployeeID EmployeeName ManagerID HierarchyLevel

----------- --------------- ----------- --------------

1 Alice NULL 0

2 Bob 1 1

5 Eve 1 1

3 Charlie 2 2

4 David 2 2

6 Frank 5 2

7 Grace 5 2

8 Henry 6 3

3. 解释with as方法查询树型结构的代码

以上代码分为两部分,第一部分定义了一个名为EmployeeHierarchy的CTE(公共表达式):

WITH EmployeeHierarchy (EmployeeID, EmployeeName, ManagerID, HierarchyLevel)

AS

(

-- Anchor member definition

SELECT EmployeeID, EmployeeName, ManagerID, 0 AS HierarchyLevel

FROM Employees

WHERE EmployeeID = 1

UNION ALL

-- Recursive member definition

SELECT e.EmployeeID, e.EmployeeName, e.ManagerID, eh.HierarchyLevel + 1

FROM EmployeeHierarchy AS eh

JOIN Employees AS e

ON eh.EmployeeID = e.ManagerID

)

其中,EmployeeHierarchy (EmployeeID, EmployeeName, ManagerID, HierarchyLevel) 定义了公共表达式的列名,它们将作为CTE的输出。

第二部分查询了EmployeeHierarchy这个CTE:

SELECT *

FROM EmployeeHierarchy;

在CTE中,第一个SELECT语句为锚定成员定义了初始记录,它选择了EmployeeID为1的员工(Alice)。第二个SELECT语句为递归成员定义了后继记录,它选择了直属于前一级员工的所有下属,直到满足停止条件。with as方法根据上述两个SELECT语句的结果来组合生成CTE的结果。

4. 使用with as方法查询Alice的直属下属

使用以下代码查询Alice的直属下属:

WITH EmployeeHierarchy (EmployeeID, EmployeeName, ManagerID, HierarchyLevel)

AS

(

SELECT EmployeeID, EmployeeName, ManagerID, 0 AS HierarchyLevel

FROM Employees

WHERE EmployeeID = 1

UNION ALL

SELECT e.EmployeeID, e.EmployeeName, e.ManagerID, eh.HierarchyLevel + 1

FROM EmployeeHierarchy AS eh

JOIN Employees AS e

ON eh.EmployeeID = e.ManagerID

)

SELECT *

FROM EmployeeHierarchy

WHERE ManagerID = 1;

输出结果如下:

EmployeeID EmployeeName ManagerID HierarchyLevel

----------- --------------- ----------- --------------

2 Bob 1 1

5 Eve 1 1

总结

本文介绍了如何使用SQL Server的with as方法查询树型结构。通过该方法,我们可以方便地查询一个节点的所有下属、父节点和祖先节点。

数据库标签