4

这是我使用“between”运算符获取日期的简单查询。

create table dummy (mydate datetime);
 insert into dummy values('2013-03-20 10:30:00.000');
 insert into dummy values('2013-03-21 10:30:00.000');
 insert into dummy values('2013-03-22 10:30:00.000');
 insert into dummy values('2013-03-23 10:30:00.000');
 insert into dummy values('2013-03-24 10:30:00.000');
 insert into dummy values('2013-03-25 10:30:00.000');
 insert into dummy values('2013-03-26 10:30:00.000');
 insert into dummy values('2013-03-27 10:30:00.000');
 insert into dummy values('2013-03-28 10:30:00.000');
 insert into dummy values('2013-03-29 10:30:00.000');
 insert into dummy values('2013-03-30 10:30:00.000');

我正在使用的 quiery 是: select * from dummy where mydate between ('3/01/2013 12:00:00 AM') and ('3/30/2013 12:00:00 AM')

在这里 2013-03-30 10:30:00.000,也应该返回。

SQL 小提琴

4

4 回答 4

15

更改 where 子句中的日期时间格式,并使用 and 检查>=<

select * 
from dummy 
where mydate >= '20130301' and
      mydate < '20130401'
于 2013-05-24T09:18:49.630 回答
3

Query:

SQLFIDDLEExample

select * 
from dummy 
where mydate between ('3/01/2013 12:00:00') 
and ('3/30/2013 12:00:00')

Result:

|                       MYDATE |
--------------------------------
| March, 20 2013 10:30:00+0000 |
| March, 21 2013 10:30:00+0000 |
| March, 22 2013 10:30:00+0000 |
| March, 23 2013 10:30:00+0000 |
| March, 24 2013 10:30:00+0000 |
| March, 25 2013 10:30:00+0000 |
| March, 26 2013 10:30:00+0000 |
| March, 27 2013 10:30:00+0000 |
| March, 28 2013 10:30:00+0000 |
| March, 29 2013 10:30:00+0000 |
| March, 30 2013 10:30:00+0000 |
于 2013-05-24T09:15:29.127 回答
2

I assume(my culture has no AM/PM designator) that the 12 AM means midnight(so from 29th to 30th). So either use 12 PM or omit the AM/PM designator.

mydate between ('3/01/2013 12:00:00 AM') 
and ('3/30/2013 12:00:00 PM')

Demo

You could also remove the time part and add one day which means midnight:

mydate between '2013-03-01' and '2013-03-31'

Demo

于 2013-05-24T09:14:37.610 回答
0

Remember, date time data uses 24hour clock (00:00:00 to 23:59:59). The mistake is in the 'AM' designation in the condition '3/30/2013 12:00:00 AM', because 12:00:00 AM is equal to 00:00:00, and 10:30:00 is "Greater than" 12:00:00 AM, that's why the value '2013-03-30 10:30:00.000' it's not in the selected values.

Use select * from dummy where mydate between ('3/01/2013 12:00:00') and ('3/30/2013 12:00:00')

于 2017-04-13T21:29:59.790 回答