1

是否可以将嵌套的 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
4

2 回答 2

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表,以避免自连接导致对基础查询的两次调用。

于 2011-02-14T16:30:01.990 回答
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
于 2011-02-14T16:29:46.623 回答