先看例子,有如下数据,3个字段分别对应的数据类型为,time_datetime是datetime类型,time_date是date类型,time_timestamp是timestamp类型:
mysql> SELECT * FROM time_type_demo; +----+---------------------+------------+---------------------+ | id | time_datetime | time_date | time_timestamp | +----+---------------------+------------+---------------------+ | 1 | 2020-08-10 23:09:29 | 2020-08-10 | 2020-08-10 23:09:45 | | 2 | 2020-08-17 23:09:58 | 2020-08-17 | 2020-08-17 23:10:06 | +----+---------------------+------------+---------------------+ 2 rows in set
进行between and查询如下:
mysql> SELECT id,time_datetime FROM time_type_demo WHERE time_datetime BETWEEN '2020-08-10' AND '2020-08-17'; SELECT id,time_date FROM time_type_demo WHERE time_date BETWEEN '2020-08-10' AND '2020-08-17'; SELECT id,time_timestamp FROM time_type_demo WHERE time_timestamp BETWEEN '2020-08-10' AND '2020-08-17'; +----+---------------------+ | id | time_datetime | +----+---------------------+ | 1 | 2020-08-10 23:09:29 | +----+---------------------+ 1 row in set +----+------------+ | id | time_date | +----+------------+ | 1 | 2020-08-10 | | 2 | 2020-08-17 | +----+------------+ 2 rows in set +----+---------------------+ | id | time_timestamp | +----+---------------------+ | 1 | 2020-08-10 23:09:45 | +----+---------------------+ 1 row in set
从结果可以看出,datetime和timestamp类型的字段进行between and查询时是不包括右边界的,date类型的包含右边界。首先明确这个结论,在应用时务必注意。
原因是什么呢?
因为MySQL对日期的查询是默认“00:00:00”,所以上面的区间实际为:2020-08-10 00:00:00——2020-08-17 00:00:00,2020-08-17 23:09:58是不在这个区间内的,所以查询不到。(严格来说不是不包括右边界,而是右边界为 00:00:00,一般时间都不在这个范围内,如果有时间为00:00:00那也包括。)
而date类型的字段是没有时分秒的,所以date类型是包括右边界的。