【问题标题】:How to get time from db depending upon conditions如何根据条件从 db 获取时间
【发布时间】:2012-06-03 15:35:39
【问题描述】:

我有一张表,其中的值是

             Table_hello
date                            col2
2012-01-31 23:01:01             a
2012-06-2  12:01:01             b
2012-06-3  20:01:01             c

现在我要选择日期

  1. 如果早于 3 天或更短时间,则以天为单位
  2. 如果是 24 小时之前或更短时间,则以小时为单位
  3. 如果是 60 分钟或更短时间,则以分钟为单位
  4. 如果是 60 秒或更短时间,则以秒为单位
  5. 在 3 天或更长时间之前采用简单格式

输出

for row1 2012-01-31 23:01:01 
for row2 1 day ago 
for row3 1 hour ago 

更新 我的sql查询

  select case 
            when TIMESTAMPDIFF(SECOND, `date`,current_timestamp) <= 60 
            then concat(TIMESTAMPDIFF(SECOND, `date`,current_timestamp), ' seconds')
            when TIMESTAMPDIFF(DAY, `date`,current_timestamp) <= 3 
            then concat(TIMESTAMPDIFF(DAY, `date`,current_timestamp), ' days')end
            when TIMESTAMPDIFF(HOUR, `date`,current_timestamp) <= 60 
            then concat(TIMESTAMPDIFF(HOUR, `date`,current_timestamp), ' hours')
            when TIMESTAMPDIFF(MINUTE, `date`,current_timestamp) <= 60 
            then concat(TIMESTAMPDIFF(MINUTE, `date`,current_timestamp), ' minutes')

from table_hello

唯一的问题是我无法在 sql 中使用 break 和 default,例如 c++ 中的 switch case

【问题讨论】:

  • 您能提供一些示例输出吗?就像上面的示例一样,您是否希望它输出 75 天、24 分钟、10 秒作为行值?你的意思是“简单格式”
  • 简单的格式是显示存储的日期
  • 如果存储为 int 而不是 datetime,为什么这会很容易? Mysql 内置了获取时差的函数。另外,您是否考虑过在应用程序级别而不是在数据库中进行这种比较?

标签: mysql sql


【解决方案1】:

为此使用timestampdiff 函数和CASE

select case 
        when TIMESTAMPDIFF(SECOND, `date`,current_timestamp) <= 60 
        then concat(TIMESTAMPDIFF(SECOND, `date`,current_timestamp), ' seconds')
        when TIMESTAMPDIFF(DAY, `date`,current_timestamp) <= 3 
        and TIMESTAMPDIFF(DAY, `date`,current_timestamp) >= 1 
        ...
       end as time_diff 
from Table_hello
where TIMESTAMPDIFF(DAY, `time`,current_timestamp) >= 3 

【讨论】:

  • 不错,但使用 5 个案例会加快我的查询速度
  • 可能有点。测试它,看看它是否对您有问题。
  • 顺便说一句,我怎么会知道 time_diff 是以天而不是小时或秒来存储时间
  • 您可以使用concat。查看我的更新日期。
  • 如果我理解正确,那么您不需要表中的所有记录。然后使用where 子句对其进行限制。看我的更新。这就是你想要的吗?
猜你喜欢
  • 2016-06-24
  • 2018-03-16
  • 2014-12-17
  • 1970-01-01
  • 2015-01-16
  • 2020-08-15
  • 2018-12-22
  • 1970-01-01
  • 2022-09-27
相关资源
最近更新 更多