10

The old DATEDIFF() allowed users to use 3 parameters, and I was trying to do this so I could get hours out of my DATEDIFF rather than days, (I'm trying to show hours since a post). In my database I'm using a TIMESTAMP and this line of code to pull a value, and obviously it doesn't work because I have the extra parameter. Once I remove the 'hour' or 'hh' the query runs and returns a value in days.

SELECT DATEDIFF(hour, CURDATE(), (SELECT Post_Date FROM Post_T WHERE pk_PostID = 1) )

Is there an easy way I can return the hourly value?

Also I'm using MYSQL Version 5.5.20.

4

1 回答 1

30

就像它在文档中说的那样:

DATEDIFF(expr1,expr2)

DATEDIFF() 返回 expr1 – expr2,表示为从一个日期到另一个日期的天数。expr1 和 expr2 是日期或日期和时间表达式。计算中仅使用值的日期部分。

如果你想在几个小时内得到结果,你应该使用Timestampdiff

TIMESTAMPDIFF(单位,datetime_expr1,datetime_expr2)

返回 datetime_expr2 – datetime_expr1,其中 datetime_expr1 和 datetime_expr2 是日期或日期时间表达式。一个表达式可以是日期,而另一个表达式可以是日期时间;日期值在必要时被视为具有时间部分“00:00:00”的日期时间。结果的单位(整数)由 unit 参数给出。

单位参数可以是: MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.

在您的情况下,您可以执行以下操作:

SELECT TIMESTAMPDIFF(hour, CURDATE(), (SELECT Post_Date FROM Post_T WHERE pk_PostID = 1) )
于 2013-09-20T21:29:35.470 回答