mysql between的邊界范圍
between 的范圍是包含兩邊的邊界值
eg: id between 3 and 7 等價與 id >=3 and id<=7
not between 的范圍是不包含邊界值
eg:id not between 3 and 7 等價與 id < 3 or id>7
1
2
3
4
5
|
select * from `test` where id between 3 and 7; 等價于 select * from `test` where id>=3 and id<=7; ----------------------------------------------------------- select * from `test` where id not between 3 and 7; 等價于 select * from `test` where id<3 or id>7; |
mysql between日期邊界的問題留意
邊界問題:
mysql, between 開始日期 and 結束日期 包含開始日期,不包含結束日期
例如:
1
|
between '2018-01-22' and '2018-01-30' |
開始日期從2018-01-22 00:00:00.0 開始, 到2018-01-29 23:59:59.59結束
表中的create_date 是varchar(21) default null comment '時間',
create_date中保存值是: 年-月-日 時:分:秒:0 例如: 2018-01-29 23:45:35.0
1
2
|
select * from test a where a.create_date between '2018-01-22' and '2018-01-30' order by a.create_date desc |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
select * from tabel a where a.create_date between '2018-01-22' and '2018-01-30' order by a.create_date desc 2018-01-29 23:45:35.0 20180129 2018-01-29 23:45:33.0 20180129 2018-01-29 00:10:58.0 20180129 2018-01-29 00:10:45.0 20180129 2018-01-28 23:42:23.0 20180128 2018-01-28 23:39:39.0 20180128 select * from tabel a where a.create_date between '2018-01-22' and '2018-01-29' order by a.create_date desc 2018-01-28 23:42:23.0 20180128 2018-01-28 23:39:39.0 20180128 2018-01-28 00:13:22.0 20180128 2018-01-28 00:13:19.0 20180128 2018-01-27 23:23:02.0 20180127 2018-01-22 00:09:59.0 20180122 2018-01-22 00:09:56.0 20180122 2018-01-22 00:01:53.0 20180122 |
遇到的其他問題:
遇到另外一張表 test2 有保存時間的字段: `reporttime` varchar(45) default null,
這個字段保存的值是:
例子1:
1
2
|
select * from bips_hpd_helpdesk a where str_to_date(from_unixtime(a.reporttime, '%y-%m-%d' ), '%y-%m-%d' ) between '2018-01-16' and '2018-01-27' order by from_unixtime(a.reporttime, '%y-%m-%d' ) desc ; |
結果1:
從結果中,可以看到取到了27號的數據,可能是處理的時間沒有 小時,分鐘,秒。
例子2:
1
2
|
select * from bips_hpd_helpdesk a where str_to_date(from_unixtime(a.reporttime, '%y-%m-%d' ), '%y-%m-%d' ) between str_to_date( '2018-01-16' , '%y-%m-%d' ) and str_to_date( '2018-01-27' , '%y-%m-%d' ) |
結果2:
找到問題: 毫秒值轉換為時間,發現這里保存的毫秒值,沒有保存時分秒:
1
2
3
4
5
6
|
from_unixtime(a.reporttime, '%y-%m-%d' ) as reporttime,a.reporttime, str_to_date(from_unixtime(a.reporttime, '%y-%m-%d' ), '%y-%m-%d %h:%i:%s' ) as reporttime22 from test a where str_to_date(from_unixtime(a.reporttime, '%y-%m-%d' ), '%y-%m-%d %h:%i:%s' ) between str_to_date( '2018-01-16' , '%y-%m-%d %h:%i:%s' ) and str_to_date( '2018-01-27 %h:%i:%s' , '%y-%m-%d' ) #subdate(curdate(),date_format(curdate(), '%w' )-1) and subdate(curdate(),date_format(curdate(), '%w' )-8) order by from_unixtime(a.reporttime, '%y-%m-%d' ) desc ; |
查看到的時間值:
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://markix.blog.csdn.net/article/details/80365585