1

我可以在 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)
4

1 回答 1

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)
                  ) ;        
于 2013-04-14T21:43:40.837 回答