0

使用 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 行的“具有 diff<2”附近使用正确的语法。

4

2 回答 2

1

您不能在 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
于 2013-12-13T10:04:32.847 回答
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

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

于 2013-12-13T09:56:28.693 回答