1. 程式人生 > >mysql使用between and處理時間區間包括右邊界

mysql使用between and處理時間區間包括右邊界

 datetime型別

CREATE TABLE `test_date` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;

‘create_time’為datetime型別

select * from test_date where create_time BETWEEN '2018-10-16' AND '2018-10-28' 

查詢出來的資料,包含‘2018-10-28 00:00:00 ’,不包括' 2018-10-28 01:00:00 '

如果是datetime的'2018-10-28' 會被轉成'2018-10-28 00:00:00'型別,所以查不出來2018-10-28的資料。

可以通過精確到秒查

select * from test_date where create_time BETWEEN '2018-10-16 00:00:00' AND '2018-10-28 23:59:59' 

date型別

CREATE TABLE `test_date` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `create_time` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;

date型別

select * from test_date where create_time BETWEEN '2018-10-16' AND '2018-10-28'