MySQL常用的日期查询总结
程序员文章站
2022-06-24 20:33:33
最近总结了一下关于日期查询里面常用到技巧,于是在此做一些相应的归纳,希望能够帮助到各位开发者们:
这里是即将用到的数据表: 数据表里面的date字段的格式为datetime类型
创建表格的sql如...
最近总结了一下关于日期查询里面常用到技巧,于是在此做一些相应的归纳,希望能够帮助到各位开发者们:
这里是即将用到的数据表: 数据表里面的date字段的格式为datetime类型
创建表格的sql如下所示:
drop table if exists `tips`; create table `tips` ( `id` int(11) not null auto_increment, `content` varchar(255) collate utf8_unicode_ci default null, `date` datetime default null, `author` varchar(255) collate utf8_unicode_ci default null, primary key (`id`) ) engine=innodb auto_increment=19 default charset=utf8 collate=utf8_unicode_ci; insert into `tips` values ('1', 'atest', '2017-10-01 20:30:13', 'idea'); insert into `tips` values ('2', 'atest', '2018-07-03 20:30:40', 'idea'); insert into `tips` values ('3', 'atest', '2018-07-12 20:30:52', 'as'); insert into `tips` values ('11', 'atest', '2018-06-23 22:01:00', 'auwigrjk'); insert into `tips` values ('12', 'atest', '2018-07-17 20:30:13', 'auwigrjk'); insert into `tips` values ('13', 'atest', '2018-07-01 20:30:13', 'auwigrjk'); insert into `tips` values ('14', 'atest', '2018-06-17 20:30:13', 'auwigrjk'); insert into `tips` values ('15', 'atest', '2018-07-03 00:00:00', 'auwigrjk'); insert into `tips` values ('16', 'atest', '2018-07-23 00:00:00', 'auwigrjk'); insert into `tips` values ('17', 'atest', '2018-07-03 00:00:00', 'auwigrjk'); insert into `tips` values ('18', 'atest', '2018-07-05 00:00:00', 'auwigrjk');
那么接下来就是一些我们在查询中经常会用到的小技巧了:
查询在某一段日期之间的数据:
select * from tips where date between '2018-07-01' and '2019-01-01'
查询在指定某一天之后的数据:
select * from tips where date>'2018-06-24'
查询30天以前的数据:
select * from tips where date>date_add(now(),interval -30 day)
查询一个月以前的数据:
select * from tips where date>date_add(now(),interval -1 month)
查询一年以前的数据:
select * from tips where date>date_add(now(),interval -1 year)
查询这个月的数据:
select * from tips where date_format(date,'%y-%m') = date_format(now(),'%y-%m')
查询今年的数据:
select * from tips where date_format(date,'%y') = date_format(now(),'%y')
获取到年月日:
select date_format(now(),"%y-%m-%d")
获取到年月日,时分秒:
select date_format(now(),"%y-%m-%d %h:%m:%s")
获取英文格式的年月日,时分秒:
select date_format(now(),"%y-%m-%d %h:%m:%s")
在不改变日期datetime类型的情况下,将所有的日期都转换为年月日格式:
select content,author,(case when date!='' then date_format(date,'%y-%m-%d') end) as date from tips order by date