1

我有一张表,其中的值是

             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

4

1 回答 1

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 
于 2012-06-03T15:43:10.370 回答