MySQL (Aurora) update timestamp using adddate or date-add or date-sub 说语法错误

MySQL (Aurora) update timestamp using adddate or date-add or date-sub says syntax error

你们谁能找出 mySQL 更新语句的语法错误是什么?

update table_name set start_time = DATE_ADD (start_time , INTERVAL 2 DAY) where start_time = '2020-12-08 10:47:00';

以上是简单的 mySQL 查询,将 start_time(时间戳)更新 2 天。

AFAIK,以上应该有效并且没有什么复杂的。但是我收到语法错误,我无法理解为什么会出现语法错误。这是我得到的错误...

Database error code: 1064. Message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') where start_time = '2020-12-08 10:47:00'' at line 10

我也尝试过其他变体,例如...

update table_name set start_time = adddate (start_time , INTERVAL 2 DAY) where start_time = '2020-12-08 10:47:00';

update table_name set start_time = date_sub (start_time , INTERVAL -2 DAY) where start_time = '2020-12-08 10:47:00';

Database error code: 1064. Message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') where start_time = '2020-12-08 10:47:00'' at line 3

如果我在 select 语句中使用 date_sub,

select * from table_name where start_time  > DATE_SUB(now() , INTERVAL 2 DAY);

它确实很有魅力。但我无法在 set =....

的更新语句中使用它

我只是无法理解出了什么问题,并且很想知道语法有什么问题。你能推荐一下吗?

看来问题出在函数名和左括号之间的 space。

这个:

DATE_ADD (start_time , INTERVAL 2 DAY)

应该写成:

DATE_ADD(start_time , INTERVAL 2 DAY)

在使用 DATE_SUB() 的示例中没有发生这种情况,因为前导 space 不存在。

并不是所有的MySQL函数都有这样的限制。这与 MySQL 解析器处理函数名的方式有关,即 described in the documentation:

The requirement that function calls be written with no whitespace between the name and the parenthesis applies only to the built-in functions that have special considerations.

DATE_ADD()DATE_SUB() 被列为受影响的函数。您可以尝试使用 SQL mode IGNORE_SPACE 来更改默认行为。

总的来说,我建议像这样使用日期算法,这样您就不必担心这样的警告(它也使代码更具可读性):

start_time + INTERVAL 2 day