Filtering on an alias in mysql

后端 未结 3 1468
清酒与你
清酒与你 2021-01-06 09:41

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         


        
相关标签:
3条回答
  • 2021-01-06 10:00

    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;
    
    0 讨论(0)
  • 2021-01-06 10:02

    Use having clause:

    SELECT (x + y) AS z, t.*  FROM t
    WHERE 
    x = 1 
    having z=2
    
    0 讨论(0)
  • 2021-01-06 10:15

    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
    
    0 讨论(0)
提交回复
热议问题