将 child 记录连接到 parent 并盛大 parents
Connect child record to parent and grand parents
项目table中的每一项都有一个departmentID,每个部门id最多可以有3个grandparents。现在我需要显示每个项目及其部门和 parents.
我进行了 3 次简单的连接,结果成功了。
SELECT tDepartment.id, tDepartment.Name, tDepartment_1.Name AS Parent1, tDepartment_2.Name AS Parent2, tDepartment_3.Name AS Parent3
FROM tDepartment AS tDepartment_3 RIGHT OUTER JOIN
tDepartment LEFT OUTER JOIN
tDepartment AS tDepartment_1 ON tDepartment.ParentID = tDepartment_1.id LEFT OUTER JOIN
tDepartment AS tDepartment_2 ON tDepartment_1.ParentID = tDepartment_2.id ON tDepartment_3.id = tDepartment_2.ParentID
ORDER BY tDepartment.Name
我的问题是,是否可以通过使用 CTE 或任何其他想法以更简洁的方式完成?
为什么左右混用?
SELECT tDepartment.id, tDepartment.Name
,tDepartment_1.Name AS Parent1
,tDepartment_2.Name AS Parent2
,tDepartment_3.Name AS Parent3
FROM tDepartment
LEFT OUTER JOIN tDepartment AS tDepartment_1
ON tDepartment.ParentID = tDepartment_1.id
LEFT OUTER JOIN tDepartment AS tDepartment_2
ON tDepartment_1.ParentID = tDepartment_2.id
LEFT OUTER JOINtDepartment AS tDepartment_3
ON tDepartment_3.id = tDepartment_2.ParentID
ORDER BY tDepartment.Name
项目table中的每一项都有一个departmentID,每个部门id最多可以有3个grandparents。现在我需要显示每个项目及其部门和 parents.
我进行了 3 次简单的连接,结果成功了。
SELECT tDepartment.id, tDepartment.Name, tDepartment_1.Name AS Parent1, tDepartment_2.Name AS Parent2, tDepartment_3.Name AS Parent3
FROM tDepartment AS tDepartment_3 RIGHT OUTER JOIN
tDepartment LEFT OUTER JOIN
tDepartment AS tDepartment_1 ON tDepartment.ParentID = tDepartment_1.id LEFT OUTER JOIN
tDepartment AS tDepartment_2 ON tDepartment_1.ParentID = tDepartment_2.id ON tDepartment_3.id = tDepartment_2.ParentID
ORDER BY tDepartment.Name
我的问题是,是否可以通过使用 CTE 或任何其他想法以更简洁的方式完成?
为什么左右混用?
SELECT tDepartment.id, tDepartment.Name
,tDepartment_1.Name AS Parent1
,tDepartment_2.Name AS Parent2
,tDepartment_3.Name AS Parent3
FROM tDepartment
LEFT OUTER JOIN tDepartment AS tDepartment_1
ON tDepartment.ParentID = tDepartment_1.id
LEFT OUTER JOIN tDepartment AS tDepartment_2
ON tDepartment_1.ParentID = tDepartment_2.id
LEFT OUTER JOINtDepartment AS tDepartment_3
ON tDepartment_3.id = tDepartment_2.ParentID
ORDER BY tDepartment.Name