5

Why doesn't the following query work? Mysql complains about z - can't I use an alias in the WHERE clause?

SELECT x + y AS z, t.*  FROM t
WHERE 
x = 1 and
z = 2

The error that I get is:

Error Code : 1054
Unknown column 'z' in 'where clause'
4

3 回答 3

12

http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

标准 SQL 不允许在 WHERE 子句中引用列别名。施加此限制是因为在评估 WHERE 子句时,可能尚未确定列值。例如,以下查询是非法的:

SELECT id, COUNT(*) AS cnt FROM tbl_name WHERE cnt > 0 GROUP BY id;

试试这个,而不是:

SELECT x + y AS z, t.* FROM t WHERE x = 1 HAVING z = 2;
于 2010-11-27T09:17:47.553 回答
4

您应该知道,使用没有GROUP BY 子句的 HAVING 子句是 MySQL 的非标准扩展,在其他数据库中不起作用。

如果您希望它是可移植的,则需要使用派生表:

选择 *
从 (
  选择 (x + y) 作为 z, t.*  
  从T
  其中 x = 1
) t2
其中 z = 2
于 2010-11-27T10:17:37.417 回答
0

使用有子句:

SELECT (x + y) AS z, t.*  FROM t
WHERE 
x = 1 
having z=2
于 2010-11-27T09:24:15.237 回答