MySQL中 BETWEEN ... AND ...
MySQL中 BETWEEN ... AND ...
1. 准备测试数据
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`age` int(11) NOT NULL,
`create_time` datetime DEFAULT NULL,
`birthday` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `test`.`student`(`id`, `name`, `age`, `create_time`, `birthday`) VALUES
(1, 'Andy', 10, '2021-02-01 00:00:00', '2021-01-30'),
(2, 'Ben', 18, '2021-02-01 00:00:01', '2021-01-31'),
(3, 'Cindy', 18, '2021-02-01 12:01:54', '2021-02-01'),
(4, 'David', 18, '2021-02-01 23:59:59', '2021-02-02'),
(5, 'Cindy2', 18, '2021-02-02 00:00:00', '2021-02-03'),
(6, 'Cindy3', 19, '2021-02-02 00:00:01', '2021-02-28'),
(7, 'Cindy4', 19, '2021-11-22 12:19:33', '2021-02-28');
2. 如果列是date
类型,则 BETWEEN ... AND ...
包含左右区间
如:筛选 生日为2021-02-01
到 2021-02-02
的学生
写法1:SELECT * FROM student WHERE birthday BETWEEN '2021-02-01' AND '2021-02-02'
写法2:SELECT * FROM student WHERE birthday >= '2021-02-01' AND birthday <= '2021-02-02'
结果均为:
3. 如果列是datetime
类型,则需分情况讨论
3.1 如果传入的参数格式为datetime
格式,则仍包含左右区间
如:筛选 create_time
为2021-02-21
的所有数据,即2021-02-01 00:00:00
至 2021-02-01 23:59:59
写法1:SELECT * FROM student WHERE create_time BETWEEN '2021-02-01 00:00:00' AND '2021-02-01 23:59:59'
写法2:SELECT * FROM student WHERE create_time >= '2021-02-01 00:00:00' AND create_time <= '2021-02-01 23:59:59'
结果均为:
3.2 如果传入的格式是date
格式,此时需要注意一些边界情况
如:需求同上,筛选 create_time
为2021-02-21
的所有数据,但不指定时分秒:
SELECT * FROM student WHERE create_time BETWEEN '2021-02-01' AND '2021-02-01'
显然数据有误,只查出来 2021-02-01 00:00:00
的数据,出现这种现象的原因,就是因为如果针对datetime
列的字段做筛选,但输入的值却是date
类型的话,默认会自动追加00:00:00
因此,上一句SQL实际上会被自动转成如下格式:
SELECT * FROM student WHERE create_time BETWEEN '2021-02-01 00:00:00' AND '2021-02-01 00:00:00'
这才出现了只查询到2021-02-01 00:00:00
的数据的情况