简体   繁体   English

MySQL-从嵌套子查询引用外部字段

[英]Mysql - reference an external field from a nested subquery

How is possible to reference an external field from a nested subquery? 如何从嵌套子查询中引用外部字段?

I'll explain better very fastly with an example: 我将通过一个示例快速地更好地解释一下:

SELECT
x
, (SELECT t1.x) as x1
/*, (SELECT x FROM (SELECT t1.x) as t2) as x2*/
FROM
(SELECT 1 as x UNION SELECT 2 as x UNION SELECT 3 as x) as t1;

If I uncomment the commented subquery, I get a "Unknown table 't1' in field list" error but I need to refer for a complex calculation to that variable from a 2-level nested subquery (it's not possible to do with a Join). 如果我取消注释注释的子查询的注释,则会收到“字段列表中的未知表't1'”错误,但我需要从2级嵌套子查询中对该变量进行复杂的计算(这与Join无关) 。

This is not possible according to MySQL manual . 根据MySQL手册,这是不可能的。 You can try using VIEWs instead of derived tables or list all your derived tables in the outermost FROM clause 您可以尝试使用VIEWs代替派生表,或在最外面的FROM子句中列出所有派生表

在此处输入图片说明

You can't use table alias in subquery, because it is out of scope. 您不能在子查询中使用表别名,因为它超出了范围。 You should (eventually) recode the subquery like this: 您应该(最终)像这样重新编码子查询:

SELECT  
    x,
    t1.x  as x1,
    (SELECT x 
     FROM (SELECT 1 as x 
           UNION 
           SELECT 2 as x 
           UNION SELECT 3 as x) as t2) as x2
FROM 
    (SELECT 1 as x 
     UNION 
     SELECT 2 as x 
     UNION 
     SELECT 3 as x) as t1;

or create a proper view and use the view for access to the data 或创建适当的视图并使用该视图访问数据

create view my_view as 

 SELECT 1 as x 
 UNION 
 SELECT 2 
 UNION 
 SELECT 3  
 ;

SELECT x
,  t1.x  as x1
, (SELECT x FROM  my_view  as t2) as x2
FROM my_view as t1
;

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

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