Home >Database >Mysql Tutorial >mysql中获取一天、一周、一月时间数据的各种sql语句写法_MySQL

mysql中获取一天、一周、一月时间数据的各种sql语句写法_MySQL

WBOY
WBOYOriginal
2016-06-01 13:12:421554browse

创建表:


create table if not exists t
(
   id int,
   addTime datetime default '0000-00-00 00:00:00′
)

添加两条初始数据:

insert t values(1, '2012-07-12 21:00:00′);
insert t values(2, '2012-07-22 21:00:00′);

一、当天或当日插入的数据:

1、传统对比判断:SELECT * FROM `t` WHERE DATE_FORMAT(addTime,'%Y-%m-%d') = date_format(now(),'%Y-%m-%d')");
2、第一点的简写:SELECT * FROM `t` WHERE addTime >= date_format(NOW(),'%Y-%m-%d');
3、利用函数判断:SELECT * FROM `t` WHERE DATEDIFF(addTime,NOW()) =0;//推荐此方法
4、利用时间戳判断:SELECT * FROM `t` WHERE addTime BETWEEN (UNIX_TIMESTAMP(now()-86440)) AND now();
注:返回当天时间的mysql函数有CURDATE()、CURRENT_DATE()、CURRENT_DATE、NOW()几种;其中NOW()获取的日期格式为0000-00-00 00:00:00的时间;CURDATE()、CURRENT_DATE()、CURRENT_DATE是获取日期格式为0000-00-00的时间,所以返回的时间无时分秒;

二、当月的相关数据写法:

1、今天是当月的第几天:SELECT DAYOFMONTH( NOW( ) );
2、获取当月的第一天时间:SELECT DATA_SUB( NOW(), INTERVAL DAYOFMONTH(NOW())

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn