MySQL DATEDIFF() 参数问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18925557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:55:33  来源:igfitidea点击:

DATEDIFF() Parameter Issue

mysqldatedatediff

提问by pcort

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.

旧的 DATEDIFF() 允许用户使用 3 个参数,我试图这样做,这样我就可以从 DATEDIFF 中获得数小时而不是数天,(我试图显示自发布以来的时间)。在我的数据库中,我使用 TIMESTAMP 和这行代码来提取一个值,显然它不起作用,因为我有额外的参数。一旦我删除了“小时”或“hh”,查询就会运行并以天为单位返回一个值。

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

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.

另外我使用的是 MYSQL 版本 5.5.20。

回答by Filipe Silva

Like it says in the documentation:

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

DATEDIFF(expr1,expr2)

DATEDIFF() returns expr1 – expr2 expressed as a value in daysfrom 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.

DATEDIFF(expr1,expr2)

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

If you want the result in hours you should use Timestampdiff

如果你想以小时为单位的结果,你应该使用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.

TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)

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

The unit argument can be: MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.

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

In your case you can do:

在你的情况下,你可以这样做:

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