如何比较MySQL中的两个DateTime字段?

时间:2021-10-08 12:01:32

You can read the question in the title. Let's say Table A have a datetime field with "2015-12-01 00:00:00" and Table B "2014-12-01 00:00:00".

你可以读标题中的问题。假设表A有一个datetime字段,“2015-12-01 00:00”,表B“2014-12-01 00:00”。

I want the data row from that table which has the bigger datetime.

我想要那个具有更大datetime的表中的数据行。

Something like "datetime(A.datetime) > datetime(B.datetime)" isn't working.

类似于“datetime(.datetime) > datetime(B.datetime)”的方法不起作用。

Help me.

帮助我。

3 个解决方案

#1


3  

When comparing two datetimes they will be interpreted as timestamps, so just doing A.datetime > B.datetime should work just fine.

当比较两个日期时间时,它们将被解释为时间戳,所以只做一个。datetime > B。datetime应该没问题。

#2


1  

You should be able to compare the datetime fields as is, A.datetime > B.datetime.

您应该能够比较datetime字段A。datetime > B.datetime。

#3


0  

You cannot always do a direct comparison using <, >, <=, >= as the answer suggests. See the MySQL docs https://dev.mysql.com/doc/refman/5.7/en/using-date.html:

您不能总是使用<、>、<=、>=进行直接比较。参见MySQL docs https://dev.mysql.com/doc/refman/5.7/en/using-date.html:

When you compare a DATE, TIME, DATETIME, or TIMESTAMP to a constant string with the <, <=, =, >=, >, or BETWEEN operators, MySQL normally converts the string to an internal long integer for faster comparison (and also for a bit more “relaxed” string checking). However, this conversion is subject to the following exceptions:

当您将日期、时间、DATETIME或时间戳与<、<=、>=、>或操作符之间的常量字符串进行比较时,MySQL通常会将字符串转换为内部的长整数,以便进行更快速的比较(同时还可以进行更“轻松”的字符串检查)。但是,这种转变有下列例外:

  • When you compare two columns
  • 当你比较两列时

#1


3  

When comparing two datetimes they will be interpreted as timestamps, so just doing A.datetime > B.datetime should work just fine.

当比较两个日期时间时,它们将被解释为时间戳,所以只做一个。datetime > B。datetime应该没问题。

#2


1  

You should be able to compare the datetime fields as is, A.datetime > B.datetime.

您应该能够比较datetime字段A。datetime > B.datetime。

#3


0  

You cannot always do a direct comparison using <, >, <=, >= as the answer suggests. See the MySQL docs https://dev.mysql.com/doc/refman/5.7/en/using-date.html:

您不能总是使用<、>、<=、>=进行直接比较。参见MySQL docs https://dev.mysql.com/doc/refman/5.7/en/using-date.html:

When you compare a DATE, TIME, DATETIME, or TIMESTAMP to a constant string with the <, <=, =, >=, >, or BETWEEN operators, MySQL normally converts the string to an internal long integer for faster comparison (and also for a bit more “relaxed” string checking). However, this conversion is subject to the following exceptions:

当您将日期、时间、DATETIME或时间戳与<、<=、>=、>或操作符之间的常量字符串进行比较时,MySQL通常会将字符串转换为内部的长整数,以便进行更快速的比较(同时还可以进行更“轻松”的字符串检查)。但是,这种转变有下列例外:

  • When you compare two columns
  • 当你比较两列时