假设我有下表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
天那密码怎么了?!~谢谢
最佳答案
您可以尝试此查询。通过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)
将IntervalMINUTE
附加到time
,让它们只有second
上的间隔时间。3.计算秒间隔。
关于mysql - 使用sql计算时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50899519/