mysql 查询具有时间间隔的日期

mysql query with between date with time interval

我有一个 table 和 created_time 字段。 需要找出特定时间间隔内两个日期之间的所有条目。 例如,如果我想查找 2018 年 4 月 1 日至 2018 年 4 月 30 日之间的所有条目,时间间隔在下午 2.30 到 4.30 之间,理想的查询是什么?

select * from my_table where created_time between '2018-04-01
14:30:00' and '2018-04-30 16:30:00'

您需要拆分比较 Date 值和 Time 值。

您可以试试这个查询。

TestDLL

CREATE TABLE my_table (
    created_time  DATETIME
);

INSERT INTO my_table VALUES ('2018-04-01 14:00:00');
INSERT INTO my_table VALUES ('2018-04-01 14:50:00');
INSERT INTO my_table VALUES ('2018-04-04 10:00:00');
INSERT INTO my_table VALUES ('2018-04-01 15:00:00');

查询

select * from my_table 
where 
    (created_time between '2018-04-01' and '2018-04-30') 
AND 
    (CAST(created_time AS time) > CAST('14:30:00' AS time) AND CAST(created_time AS time) < CAST('16:30:00' AS time))

[结果]:

|         created_time |
|----------------------|
| 2018-04-01T14:50:00Z |
| 2018-04-01T15:00:00Z |

SQLFiddle