在进一步的子查询中引用(基于子查询)别名

时间:2013-04-14 21:25:27

标签: mysql sql

我可以在where子句的第二个子查询中引用从FROM子句中的子查询创建的别名吗?

Select x FROM 
((SELECT x,y FROM A) UNION (SELECT x,y FROM B) UNION (SELECT x,y FROM C)) AS newAlias 
WHERE y IN (SELECT MAX(y) FROM newAlias)

1 个答案:

答案 0 :(得分:1)

不,答案是否定的。必须重复NewAlias子查询。

有可能使用CTE(公用表表达式)但MySQL尚未实现它们:

WITH newAlias AS
  (SELECT x,y FROM A UNION SELECT x,y FROM B UNION SELECT x,y FROM C)
SELECT x 
FROM newAlias 
WHERE y = (SELECT MAX(y) FROM newAlias) ;

在MySQL中,你必须重复子查询:

SELECT x 
FROM 
  (SELECT x,y FROM A UNION SELECT x,y FROM B UNION SELECT x,y FROM C) 
  AS newAlias 
WHERE y = 
      ( SELECT MAX(y) 
        FROM
          (SELECT x,y FROM A UNION SELECT x,y FROM B UNION SELECT x,y FROM C) 
          AS newAlias  
      ) ;

当然,您通常可以重写 - 重新构造查询。一种方法:

SELECT x 
FROM 
  (SELECT x,y FROM A UNION SELECT x,y FROM B UNION SELECT x,y FROM C) 
  AS newAlias 
WHERE y = GREATEST( (SELECT MAX(y) FROM A)
                  , (SELECT MAX(y) FROM B)
                  , (SELECT MAX(y) FROM C)
                  ) ;