SQL Server 中的递归自连接
在 SQL Server 中,递归自连接允许您通过连接基于父子关系多次将表连接到自身。
执行递归自连接检索与特定层次结构相关的记录,可以采用以下策略:
使用公共表表达式(CTE)
CTE,也称为递归查询,可用于实现递归自连接。核心思想是定义一个锚查询,选择满足特定条件(例如,没有父记录)的记录,然后使用递归子查询将子记录附加到结果中:
WITH q AS ( SELECT * FROM mytable WHERE ParentID IS NULL UNION ALL SELECT m.* FROM mytable m JOIN q ON m.parentID = q.PersonID ) SELECT * FROM q
通过添加排序递归子查询的条件,树顺序可以是保留:
WITH q AS ( SELECT m.*, CAST(ROW_NUMBER() OVER (ORDER BY m.PersonId) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc FROM mytable m WHERE ParentID IS NULL UNION ALL SELECT m.*, q.bc + '.' + CAST(ROW_NUMBER() OVER (PARTITION BY m.ParentID ORDER BY m.PersonID) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN FROM mytable m JOIN q ON m.parentID = q.PersonID ) SELECT * FROM q ORDER BY bc
注意事项:
以上是SQL Server 中的递归自连接如何有效地导航分层数据?的详细内容。更多信息请关注PHP中文网其他相关文章!