我正在使用 MySQL 8,并试图获取当前时间与数据库表中名为“created_on
”的字段之间的时差。如果差异小于 180 秒,我需要查询返回秒数。如果分钟数 > 180 且 < 60,则打印分钟数。
以下查询不断显示 1064 错误代码:
select current_timestamp, created_on,
case
when timestampdiff(second, created_on, current_timestamp) <= 180 then " seconds ago"
when timestampdiff(minute, created_on, current_timestamp) > 3 AND < 60 then " minutes ago"
else ''
end
from whp;
任何人都可以提供有关如何纠正此问题的建议吗?
最佳答案
像这样:
select
current_timestamp,
created_on,
case
when timestampdiff(second, created_on, current_timestamp) <= 180 then " seconds ago"
when timestampdiff(minute, created_on, current_timestamp) < 60 then " minutes ago"
else ''
end
from whp;
对于 case 语句,它使用条件匹配的第一个 when
。您不需要测试 > 3 分钟,因为 <= 180 秒的第一场比赛将拾取该时间。如果在某些情况下您确实需要一个范围,则需要按以下方式使用 and
select
current_timestamp,
created_on,
case
when timestampdiff(second, created_on, current_timestamp) <= 180 then " seconds ago"
when timestampdiff(minute, created_on, current_timestamp) > 3 and
timestampdiff(minute, created_on, current_timestamp) < 60 then " minutes ago"
else ''
end
from whp;
关于mysql - 如何修复带有 timestampdiff 错误 1064 的 case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70755118/