使用sql计算时间

oxcyiej7  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(290)

假设我有下表 test 它有很多列 id , time , post 这是它拥有的数据样本。

-----------------------------------
   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 打印出来的天数
那么代码怎么了?!~谢谢您

mjqavswn

mjqavswn1#

您可以尝试此查询。计算间隔 TIMESTAMPDIFF 以及 TIMESTAMPADD 功能。

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 让我们一步一步了解它:
1 TIMESTAMPDIFF(MINUTE, time, NOW()) 获取间隔 MINUTE 介于 time 以及 NOW() 2 TIMESTAMPADD(MINUTE, TIMESTAMPDIFF(MINUTE, time, NOW()), time) 追加间隔 MINUTEtime ,让他们只有间隔时间 second .
3.计算秒间隔。

qnakjoqk

qnakjoqk2#

对于查询中缺少的部分(年和月),可以使用带有日期的timestampdiff\u 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演示

相关问题