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

标签 mysql syntax-error where-clause 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<2”附近使用的正确语法。

最佳答案

您不能在 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 

更多细节

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

关于mysql - 为什么mysql的where子句中不能使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20563489/

相关文章:

mysql - 根据冲突条件查找行

mysql - 无法在表名中创建带下划线的表 MySQL v5.5.14

python - 无法分配给函数调用 Error-Python

mysql where inet_aton like %...%

F#存在哪里函数?

mysql - 如何在R中重写mysql服务器上的数据表?

mysql - SQL GROUP BY 返回空集

java - 错误 FROM 关键字未在预期位置找到

mysql - 真的很简单的MySQL JOIN无法正常工作吗?

MySQL - 仅选择那些没有其他值的