假设我有下表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
天打印出来的
那么代码出了什么问题?! 〜谢谢你
答案 0 :(得分:2)
您可以尝试此查询。按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)
向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`;