如何在sql中将选定的日期列格式化为相对时间格式

gr8qqesn  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(529)

如果我们有一个带有时间戳字段的表,我想将日期显示为 time ago (类似于我们在java/php中的做法)
在mysql中有没有现成的函数来完成这个任务?
输出应该是相对时间,而不是通常的日期时间 0000-00-00 00:00:00 ```
USER | LAST_LOGGED_IN


  1. ABC | 5 minutes ago

  1. PQR | 10 minutes ago

  1. XYZ | 2 weeks ago

  1. XXX | 1 month ago
gopyfrb3

gopyfrb31#

使用timestampdiff函数:

  1. select
  2. t.userid,
  3. case when t.years > 0
  4. then concat( t.years ,' year', case when t.years > 1
  5. then 's' else '' end, ' ago')
  6. when t.months > 0
  7. then concat( t.months, ' month', case when t.months > 1
  8. then 's' else '' end, ' ago')
  9. when t.weeks > 0
  10. then concat( t.weeks , ' week', case when t.weeks > 1
  11. then 's' else '' end, ' ago')
  12. when t.days > 0
  13. then concat( t.days , ' day', case when t.days > 1
  14. then 's' else '' end, ' ago')
  15. when t.hours > 0
  16. then concat( t.hours, ' hour', case when t.hours > 1
  17. then 's' else '' end, ' ago')
  18. when t.minutes > 0
  19. then concat( t.minutes, ' minute', case when t.minutes > 1
  20. then 's' else '' end, ' ago')
  21. else concat( t.seconds, ' second', case when t.seconds > 1
  22. then 's' else '' end, ' ago')
  23. end as last_login
  24. from
  25. (
  26. select
  27. userid,
  28. timestampdiff(second, login_time, now()) as seconds,
  29. timestampdiff(minute, login_time, now()) as minutes,
  30. timestampdiff(hour, login_time,now()) as hours,
  31. timestampdiff(day, login_time,now()) as days,
  32. timestampdiff(week, login_time,now()) as weeks,
  33. timestampdiff(month, login_time, now()) as months,
  34. timestampdiff(year, login_time, now()) as years
  35. from user_login ) t

sqlfiddle:http://sqlfiddle.com/#!9/a2cbee/5号

展开查看全部

相关问题