使用sql计算时间

时间:2018-06-17 18:48:04

标签: mysql sql

假设我有下表test,它有idtimepost列,这是它拥有的数据样本。

-----------------------------------
   id           time        post
-----------------------------------     
    1   2018-06-17 16:12:30 post1
    2   2018-06-17 16:13:09 post2
    3   2017-06-15 16:12:30 post7
----------------------------------

我希望仅使用SQL打印出自每个帖子添加到数据库以来的天数,小时数,分钟数和秒数

好的,这是我第一次尝试

SELECT
    id,
    time,
    NOW(),
    CONCAT (
    FLOOR(TIME_FORMAT(SEC_TO_TIME(NOW() - `time`), '%H') / 24),
    ' Days ',
    MOD (TIME_FORMAT(SEC_TO_TIME(NOW() - `time`), '%H'), 24),
    ' Hours ',
    TIME_FORMAT(SEC_TO_TIME(NOW() - `time`), '%i Minutes %s Seconds'),
    ' ago' 
    ) AS `ago` 
FROM
    `test`;

但它似乎没有给出正确的计算,例如上面样本的输出是

1   2018-06-17 16:12:30 2018-06-17 20:38:08 0 Days 11 Hours 49 Minutes 38 Seconds ago
2   2018-06-17 16:13:09 2018-06-17 20:38:08 0 Days 11 Hours 48 Minutes 19 Seconds ago
3   2017-06-15 16:12:30 2018-06-17 20:38:08 34 Days 22 Hours 59 Minutes 59 Seconds ago

你可以看到,在id = 3中,差异应该不仅仅是34天打印出来的

那么代码出了什么问题?! 〜谢谢你

2 个答案:

答案 0 :(得分:2)

您可以尝试此查询。按TIMESTAMPDIFFTIMESTAMPADD函数计算间隔。

SELECT
    id,
    time,
    NOW(),
    CONCAT (
    TIMESTAMPDIFF(DAY,`time`, NOW()),' Days ',
    TIMESTAMPDIFF(HOUR, TIMESTAMPADD(DAY, TIMESTAMPDIFF(DAY, `time`, NOW()), `time`), NOW()),' Hours ',
    TIMESTAMPDIFF(MINUTE, TIMESTAMPADD(HOUR, TIMESTAMPDIFF(HOUR, `time`, NOW()), `time`), NOW()), ' Minutes ',
    TIMESTAMPDIFF(SECOND, TIMESTAMPADD(MINUTE, TIMESTAMPDIFF(MINUTE, `time`, NOW()), `time`), NOW()), ' Seconds '
    ' ago' ) AS `ago` 
FROM
    `test`;

sqlfiddle:http://sqlfiddle.com/#!9/5e8085/2

注意

例如,您希望在SECOND

上获得Interval

让我们一步一步地了解它:

1. TIMESTAMPDIFF(MINUTE, time, NOW())MINUTEtime

之间获得间隔NOW()

2. TIMESTAMPADD(MINUTE, TIMESTAMPDIFF(MINUTE, time, NOW()), time)MINUTE添加Interval time,让他们在second上只有Interval时间。

3.计算秒的间隔时间。

答案 1 :(得分:1)

您可以将TIMESTAMPDIFF与DATE_ADD一起用于查询的缺失部分():

SELECT CONCAT (TIMESTAMPDIFF(YEAR, `time`, NOW()),' Year ',
           TIMESTAMPDIFF(MONTH, DATE_ADD(`time`, 
                        INTERVAL TIMESTAMPDIFF(YEAR, `time`, NOW()) YEAR), NOW()),
           ' Month ') as "Time(Year|Month)"
 FROM `test`;

SQL Fiddle Demo