当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL常用的日期查询总结

MySQL常用的日期查询总结

2018年09月14日  | 移动技术网IT编程  | 我要评论

古代地主婆养成攻略,3500左右的电脑配置,上海游艇会

最近总结了一下关于日期查询里面常用到技巧,于是在此做一些相应的归纳,希望能够帮助到各位开发者们:

这里是即将用到的数据表: 数据表里面的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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网