简体   繁体   English

从内部联接中的子查询访问表 - MySql

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

I am having an SQL query as follows -我有一个 SQL 查询如下 -

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' “where 子句”中的未知列“AA.id”

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.在 MySQL 的连接子查询中不能引用外部别名。 In PostgreSQL you could use CROSS JOIN LATERAL and in SQL Server CROSS APPLY , however, there is no such thing in MySQL.在 PostgreSQL 中,您可以使用CROSS JOIN LATERAL和 SQL Server CROSS APPLY ,但是,在 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 ).假设您没有将FROM子句中的子查询编写为临时视图,而是使其成为显式视图B1 (使用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 .此外, B1 select 不包含一个aid ,只有一个bid和一个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.最后, AAAON子句不包含对表AAA任何引用,因此这实际上不是该表的连接标准。

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 :-)这可能很简单,你把事情复杂化了:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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