1

Is it allowed to reference external field from nested select?

E.g.

SELECT
FROM ext1
LEFT JOIN (SELECT * FROM int2 WHERE int2.id = ext1.some_id ) as x ON 1=1

in this case, this is referencing ext1.some_id in nested select. I am getting errors in this case that field ext1.some_id is unknow. Is it possible? Is there some other way?

UPDATE:

Unfortunately, I have to use nested select, since I am going to add more conditions to it, such as LIMIT 0,1 and then I need to use a second join on the same table with LIMIT 1,1 (to join another row) The ultimate goal is to join 2 rows from the same table as if these were two tables So I am kind of going to "spread" a few related rows into one long row.

0

3 Answers 3

2

The answer to your initial question is: No, remove your sub-query and put the condition into the ON-clause:

SELECT *
FROM ext1
LEFT JOIN int2 ON ( int2.id = ext1.some_id )

One solution could be to use variables to find the first (or second) row, but this solution would not work efficiently with indexes, so you might end up with performance problems.

SELECT ext1.some_id, int2x.order_col, int2x.something_else
FROM ext1
LEFT JOIN (SELECT `int2`.*, @i:=IF(@id=(@id:=id), @i+1, 0) As rank
           FROM `int2`,
           ( SELECT @i:=0, @id:=-1 ) v
              ORDER BY id, order_col ) AS int2x ON (     int2x.id = ext1.some_id
                                                             AND int2x.rank = 0 )
;

This assumes that you have a column that you want to order by (order_col) and Left Joins the first row per some_id.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, I have to use nested select, since I am going to add more conditions to it, such as LIMIT 0,1 and then I need to use a second join on the same table with LIMIT 1,1 The ultimate goal is to join 2 rows from the same table as if these were two tables
0

Do you mean this?

SELECT ...
FROM ext1
LEFT JOIN int2 ON int2.id=ext1.some_id

Comments

0

That's what the ON clause is for:

SELECT
FROM ext1
LEFT JOIN int2 AS x ON x.id = ext1.some_id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.