简体   繁体   中英

Accessing table from a sub-query inside an inner join - MySql

I am having an SQL query as follows -

select 
* 
from A
inner join AA on A.id = AA.aid
inner join AAA on 
(
  select B.bid, B.bname 
  from B
  inner join C on B.id = C.bid
  where C.aaid = AA.id
) as B1 on A.id = B1.aid

Which gives an error

Unknown column 'AA.id' in 'where clause'

It will be very helpful if someone can tell me the reason and provide me with a possible solution.

I believe that you need something like this

select 
* 
from A
inner join AA on A.id = AA.aid
inner join AAA on AA.id = AAA.aid 
inner join
(
  select B.bid, B.bname, C.aaid
  from B
  inner join C on B.id = C.bid
) as B1 on A.id = B1.aid and AA.id = B1.aaid

It is not possible to reference outer aliases in join subqueries in MySQL. In PostgreSQL you could use CROSS JOIN LATERAL and in SQL Server CROSS APPLY , however, there is no such thing in MySQL.

From my understanding,

select 
* 
from #a1 a1 --A
inner join #a2 a2 on a1.i = A2.i --AA
inner join #a3 a3 on a1.i = a3.i --AAA
inner join
(
  select B.i, a2.i ai
  from #b b --B
  inner join #c c on B.i = C.i --C
  inner join #a2 a2 on a2.i = C.i  --AA
) as B1 
on A1.i = B1.i
and B1.ai = a2.i

Lack of sample data, we help as assumption.

Revert me, if query needs updates.

This is too long for a comment, so ...

Let's say you didn't write the subquery in the FROM clause as an ad-hoc view, but make it an explicit view B1 (with CREATE VIEW ). Then your query would read

select * 
from A
inner join AA on A.id = AA.aid
inner join AAA on B1 on A.id = B1.aid

which illustrates that your syntax is off.

Moreover the B1 select doesn't contain an aid , only a bid and a bname .

At last the ON clause for AAA doesn't contain any reference to the table AAA , so this is not really a join criteria for that table.

This is the answer to what's wrong with your query. I cannot show you the correct query, though, because it's completely unclear what you are trying to achieve. Please elaborate. It's probably quite simple and you're over-complicating things :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM