如何在mysql中的两个日期之间获取日期?

时间:2012-08-06 11:14:13

标签: mysql

在MySql数据库中有AM_TIMETABLE

UserId        DateTime
 101        2012-08-08 04:00:00 
 102        2012-08-15 10:00:00
 103        2012-08-18 09:00:00
 104        2012-08-24 05:00:00

我的问题是,我正在通过开始日期和结束日期,然后我将获得DateTime列日期 例如:

select * from AM_TIMETABLE where DateTime<='2012-08-08 00:00:00' and DateTime>='2012-08-20 00:00:00'

然后我将得到101,102,103 UserId的值。 但我收到错误please help

6 个答案:

答案 0 :(得分:4)

BETWEEN对此更好。并且您还必须转义DateTime,因为它是一个保留字。

SELECT * 
FROM   AM_TIMETABLE 
WHERE  `DateTime` BETWEEN '2012-08-08 00:00:00' AND '2012-08-20 00:00:00'

答案 1 :(得分:2)

这可能会更好:

select * from AM_TIMETABLE where `DateTime`<='2012-08-20 00:00:00' and `DateTime`>='2012-08-08 00:00:00'

DateTime也可能是一个保留字,对此不太确定。如果是这种情况,你需要围绕它们的反引号(单个`之前和之后)

答案 2 :(得分:0)

日期时间字段必须在引号内:

SELECT * 
FROM AM_TIMETABLE 
WHERE `DateTime` <= '2012-08-08 00:00:00' AND 
      `DateTime` >= '2012-08-20 00:00:00';

或者您可以尝试:

SELECT * 
FROM AM_TIMETABLE 
WHERE `DateTime` NOT BETWEEN '2012-08-08 00:00:00' AND '2012-08-20 00:00:00';

答案 3 :(得分:0)

您需要引用日期时间值。

答案 4 :(得分:0)

你必须把日期用引号

   set @start_date='2012-08-08 00:00:00';
   set @end_date='2012-08-20 00:00:00';
   select * from AM_TIMETABLE where DateTime<=@start_date and DateTime>=@end_date

答案 5 :(得分:0)

SELECT * FROM AS_TIMETABLE WHERE DateTime BETWEEN CAST('2012-08-08 00:00:00' AS DATETIME) AND CAST('2012-08-08 00:00:00' AS DATETIME);