Self-join with nested select query in T-SQL
문제
Is it possible to join a nested select statement with itself (without writing it out twice and running it twice)
Something like this would be ideal
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
해결책
50% possible. You can use a CTE to avoid writing it twice but it will still execute twice.
;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
If the query is expensive you would need to materialize it into a table variable or #temp
table to avoid the self join causing two invocations of the underlying query.
다른 팁
You could use a common table expression:
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
제휴하지 않습니다 StackOverflow