为什么变量不能用在mysql的where子句中

时间:2013-12-13 09:53:12

标签: mysql syntax-error where having clause

使用Mysql这个语句有效:

SELECT *, ABS(UNIX_TIMESTAMP(time) - 
       UNIX_TIMESTAMP('2013-11-14 14:35:21') ) as diff from Alert
order by diff
limit 3

但如果我按如下方式添加一个where子句,它会在'where子句'中给出“未知列'diff'”错误

SELECT *, ABS(UNIX_TIMESTAMP(time) - 
       UNIX_TIMESTAMP('2013-11-14 14:35:21') ) as diff from Alert
where diff < 2
order by diff
limit 3

好的我将语句更改为使用Having子句,如下所示:

SELECT *, ABS(UNIX_TIMESTAMP(time) - 
       UNIX_TIMESTAMP('2013-11-14 14:35:21') ) as diff from Alert
order by diff
having diff<2

它还在给我你的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第4行的'having diff&lt; 2'附近使用正确的语法。

2 个答案:

答案 0 :(得分:1)

你不能在where子句中使用别名,但是它的顺序是有效的,因为在查询获取完整结果之后会发生顺序。

您的第三个查询是错误的,因为我认为正确的语法首先按

排序
SELECT *, ABS(UNIX_TIMESTAMP(time) - UNIX_TIMESTAMP('2013-11-14 14:35:21') ) as diff 
from Alert having diff<2 order by diff 

更多细节

WHERE is used while listing and no ALIAS names are available yet

HAVING filters rows after listing all possible rows so ALIAS names are generated

答案 1 :(得分:0)

使用

SELECT *, ABS(UNIX_TIMESTAMP(time) - UNIX_TIMESTAMP('2013-11-14 14:35:21') ) as diff 
from Alert 
order by 
    ABS(UNIX_TIMESTAMP(time) - UNIX_TIMESTAMP('2013-11-14 14:35:21') ) 
limit 3

您不能按顺序by(或where)子句使用命名列计算。