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

为什么mysql的where子句中不能使用变量,mysql,syntax-error,where,having,clause,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\u时间戳) UNIX_时间戳('2013-11-14 14:35:21')与警

使用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\u时间戳)
UNIX_时间戳('2013-11-14 14:35:21')与警报不同
其中diff<2
按差异订购
限制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
SELECT*,ABS(UNIX\u时间戳)
UNIX_时间戳('2013-11-14 14:35:21')与警报不同
按差异订购
有不同的用法


您不能在order by(或where)子句中使用命名列计算。

您不能在where子句中使用别名,但在order by中它可以工作,因为order by发生在查询获取完整结果之后

您的第三个查询给出了错误,因为我认为正确的语法是先有,然后按顺序

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