Filtering on an alias in mysql

ぐ巨炮叔叔 提交于 2019-12-01 01:13:23
NSSec

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

Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. For example, the following query is illegal:

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

Try this, instead:

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

You should be aware that the usage of the HAVING clause without a GROUP BY clause is a non-standard extension of MySQL and won't work in other databases.

If you want this to be portable, you need to use a derived table:

SELECT *
FROM (
  SELECT (x + y) AS z, t.*  
  FROM t
  WHERE x = 1 
) t2
WHERE z = 2

Use having clause:

SELECT (x + y) AS z, t.*  FROM t
WHERE 
x = 1 
having z=2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!