日期时间比较mysql

时间:2012-09-25 07:54:02

标签: mysql datetime

我想做一个简单的日期& MySQL中的时间比较。这样的事情:

IF( NOW() > Ticket.fixTime ),日期格式如下

IF(2012-09-25 08:47:25  >  2012-09-24 18:15:16)

然而,这会返回错误的结果。

有关如何实现这一目标的任何建议?

谢谢!

2 个答案:

答案 0 :(得分:1)

你必须这样:

IF( TO_SECONDS(NOW()) > TO_SECONDS(Ticket.fixTime) )

解释

您可以使用TO_SECONDS将时间转换为秒并进行比较。

IF('TO_SECONDS(2012-09-25 08:47:25') > TO_SECONDS('2012-09-24 18:15:16'))

输出

输出为binary,即10

mysql> SELECT TO_SECONDS('2012-09-25 08:47:25') > TO_SECONDS('2012-09-24 18:15:16');
+-----------------------------------------------------------------------+
| TO_SECONDS('2012-09-25 08:47:25') > TO_SECONDS('2012-09-24 18:15:16') |
+-----------------------------------------------------------------------+
|                                                                     1 |
+-----------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TO_SECONDS('2012-09-25 08:47:25') < TO_SECONDS('2012-09-24 18:15:16');
+-----------------------------------------------------------------------+
| TO_SECONDS('2012-09-25 08:47:25') < TO_SECONDS('2012-09-24 18:15:16') |
+-----------------------------------------------------------------------+
|                                                                     0 |
+-----------------------------------------------------------------------+
1 row in set (0.00 sec)

IF条件

IF条件应该以这种方式使用:

mysql> SELECT IF (TO_SECONDS('2012-09-25 08:47:25') < TO_SECONDS('2012-09-24 18:15:16'), 'True', 'False');
+---------------------------------------------------------------------------------------------+
| IF (TO_SECONDS('2012-09-25 08:47:25') < TO_SECONDS('2012-09-24 18:15:16'), 'True', 'False') |
+---------------------------------------------------------------------------------------------+
| False                                                                                       |
+---------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT IF (TO_SECONDS('2012-09-25 08:47:25') > TO_SECONDS('2012-09-24 18:15:16'), 'True', 'False');
+---------------------------------------------------------------------------------------------+
| IF (TO_SECONDS('2012-09-25 08:47:25') > TO_SECONDS('2012-09-24 18:15:16'), 'True', 'False') |
+---------------------------------------------------------------------------------------------+
| True                                                                                        |
+---------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

答案 1 :(得分:0)

Mysql IF语句用作

IF(condition, valueA, valueB) // valueA for condition is true otherwise valueB

所以你应该像:

一样使用它
SELECT IF(NOW() > Ticket.fixTime, 'what you want to show', 'i do not know')
FROM your_table

或者您对IFwhere感到困惑,只是想要

SELECT * FROM your_table WHERE NOW() > Ticket.fixTime