两个日期之间的MYSQL搜索

时间:2013-06-12 04:43:02

标签: mysql sql

我在数据库中有两个日期:

from_dateTime = 2013-06-12
to_dateTime   = 2013-07-10

我想搜索from_dateTimeto_dateTime之间的所有记录。我试着在mysql中使用以下代码:

SELECT *
FROM users i
WHERE i.from_dateTime >= '2013-06-12' AND i.to_dateTime <= '2013-07-10'

但它没有像我预期的那样奏效。为什么我得到空结果集?

更新

from_dateTime = 2013-06-11
to_dateTime   = 2013-06-12

SQL:

SELECT * FROM users i WHERE  NOW() between i.from_dateTime AND i.to_dateTime 

NOW()2013-06-12 08:17:13,命令也无法找到我的记录。

4 个答案:

答案 0 :(得分:3)

问题在于您要比较日期和日期时间。日期从午夜开始。任何时间组件都大于相应的日期。试试这个:

SELECT *
FROM users u
WHERE date(NOW()) between u.from_dateTime AND u.to_dateTime 

答案 1 :(得分:1)

SELECT * 
FROM users i 
WHERE cast(NOW() as date) 
      between i.from_dateTime AND i.to_dateTime

<强> SQL FIDDLE

答案 2 :(得分:0)

select from table_name where datetime_column >= '2013-06-11' and datetime_column <= '2013-06-12'

答案 3 :(得分:0)

使用between

SELECT * FROM users u where date(NOW()) between u.from_dateTime and u.to_dateTime