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

时间:2018-07-22 15:51:00

标签: mysql nested subquery

如何从嵌套子查询中引用外部字段?

我将通过一个示例快速地更好地解释:

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;

如果我取消注释注释的子查询的注释,则会收到“字段列表中的未知表't1'”错误,但我需要从2级嵌套子查询中对该变量进行复杂的计算(这与加入)。

2 个答案:

答案 0 :(得分:0)

根据MySQL manual,这是不可能的。您可以尝试使用VIEWs代替派生表,或在最外面的FROM子句中列出所有派生表

enter image description here

答案 1 :(得分:0)

您不能在子查询中使用表别名,因为它不在范围内。您最终应该像这样重新编码子查询:

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;

或创建适当的视图并使用该视图访问数据

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
;