是否可以将嵌套的select语句与自身连接(无需将其写出两次并运行两次)
这样的事情是理想的
SELECT P.Child, P.Parent, Q.Parent AS GrandParent
FROM (SELECT Child, Parent FROM something-complex) AS P
LEFT JOIN P AS Q ON Q.Child = P.Parent
答案 0 :(得分:4)
50%可能。您可以使用CTE避免两次写入,但仍然会执行两次。
;WITH p
AS (SELECT child,
parent
FROM something-complex)
SELECT p.child,
p.parent,
q.parent AS grandparent
FROM p
LEFT JOIN p AS q
ON q.child = p.parent
如果查询很昂贵,您需要将其具体化为表变量或#temp
表,以避免自连接导致对基础查询的两次调用。
答案 1 :(得分:2)
您可以使用公用表表达式:
WITH P AS (SELECT Child, Parent FROM something-complex)
SELECT P.Child, P.Parent, Q.Parent as GrandParent
LEFT JOIN P AS Q ON Q.Child = P.Parent