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'
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'
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;
您应该知道,使用没有GROUP BY 子句的 HAVING 子句是 MySQL 的非标准扩展,在其他数据库中不起作用。
如果您希望它是可移植的,则需要使用派生表:
选择 * 从 ( 选择 (x + y) 作为 z, t.* 从T 其中 x = 1 ) t2 其中 z = 2
使用有子句:
SELECT (x + y) AS z, t.* FROM t
WHERE
x = 1
having z=2