最近总结了一下关于日期查询里面常用到技巧,于是在此做一些相应的归纳,希望能够帮助到各位开发者们:
这里是即将用到的数据表: 数据表里面的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 复制代码
mysql查询每一天某个时间段的所有记录(例:9:00:00到21:00:00):
SELECT * FROM 表名 WHERE DATE_FORMAT(create_time,'%H:%i:%S')>='09:00:00' and DATE_FORMAT(create_time,'%H:%i:%S')<='21:00:00' ORDER BY 排序字段 ASC;