Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join a subquery to itself?

How do can you join a subquery onto itself? I'd like to do something like the following.

SELECT 
    four.src AS start, four.dest AS layover, f.dest AS destination
FROM 
    ( SELECT 1 AS src, 2 as dest union all select 2, 3 ) AS four
JOIN
    four AS f 
ON f.src = four.dest 

However the query above gives me the error

Msg 208, Level 16, State 1, Line 1 Invalid object name 'four'.

I'd rather not have to store it as a variable or view etc first since this is part of a monolithic query (this is itself a subquery and its part of a series of UNIONS) and I do not want to make sure that there are no impacting joins elsewhere that relate.

The force behind this change is that fourused to be a simple lookup but now for this query the values have to be calculated.


PS - this is a simplified example, in my case the subquery for four is a hundred lines long

like image 276
Sled Avatar asked Oct 19 '25 04:10

Sled


2 Answers

You can make use of CTE (Common Table Expression in this scenario. Here, you need not to store this result in any temporary objects.

;WITH four AS (
SELECT 1 AS src, 2 as dest 
union all 
select 2, 3
)

SELECT F1.src AS start, F1.dest AS layover, f2.dest AS destination
FROM four F1
INNER JOIN four F2 ON F1.src = F2.dest 
like image 51
Shakeer Mirza Avatar answered Oct 21 '25 18:10

Shakeer Mirza


Use a temp table.

Declare @Temp(src int, desc int);
INSERT INTO @Temp(src,desc)
VALUES
(SELECT 1 AS src, 2 as dest union all select 2, 3)
SELECT * FROM @Temp t1
INNER JOIN @Temp t2 ON t1.src = t2.dest
like image 33
A W Avatar answered Oct 21 '25 17:10

A W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!