旧的 DATEDIFF() 允许用户使用 3 个参数,我试图这样做是为了从我的 DATEDIFF 中获取小时数而不是天数(我试图显示自发布后的小时数)。在我的数据库中,我使用 TIMESTAMP 和这行代码来提取一个值,显然它不起作用,因为我有额外的参数。一旦我删除了“小时”或“hh”,查询就会运行并返回一个以天为单位的值。
SELECT DATEDIFF(hour, CURDATE(), (SELECT Post_Date FROM Post_T WHERE pk_PostID = 1) )
有没有一种简单的方法可以返回每小时值?
另外,我使用的是 MYSQL 版本 5.5.20。
最佳答案
就像 documentation 中所说的那样:
DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 – expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.
如果您想要以小时为单位的结果,您应该使用 Timestampdiff
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns datetime_expr2 – datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument.
单位参数可以是:MICROSECOND(微秒)、SECOND、MINUTE、HOUR、DAY、WEEK、MONTH、QUARTER 或 YEAR。
在你的情况下你可以这样做:
SELECT TIMESTAMPDIFF(hour, CURDATE(), (SELECT Post_Date FROM Post_T WHERE pk_PostID = 1) )
关于mysql - DATEDIFF() 参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18925557/