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

7y4bm7vi  于 2023-08-02  发布在  Mysql
关注(0)|答案(6)|浏览(100)

在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

字符串
我的问题是,我传递start-date和end-date,然后我将得到ex的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

zzlelutf

zzlelutf1#

BETWEEN对这个要好得多。你还必须转义DateTime,因为它是保留字。

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

字符串

c8ib6hqw

c8ib6hqw2#

这样做可能会更好:

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

字符串
DateTime也可能是一个保留字,对此不太确定。如果是这样的话,你需要在它们周围加上反引号(一个单独的` before和after)

kg7wmglp

kg7wmglp3#

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

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';

pvcm50d1

pvcm50d14#

您需要在日期时间值上加上引号。

chhkpiq4

chhkpiq45#

你得把日期用引号括起来

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

字符串

x4shl7ld

x4shl7ld6#

你可以像这样在between关键字中使用强制转换。我认为这是最好的办法

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);

字符串

相关问题