`

mysql 对取当前日期周一和周日语句的详细解析

 
阅读更多

网上对于用mysql取当前日期周一和周日的方法非常多,但基本上都只有一个方法,没有什么解释,后果就是会用,但为什么要这样用,就不一定知道了。

自己研究了下,写点东西,避免遗忘

 

 

 

select subdate(curdate(),date_format(curdate(),'%w')-1)//获取当前日期在本周的周一

select subdate(curdate(),date_format(curdate(),'%w')-7)//获取当前日期在本周的周日

这两句语句是mysql用来取当前日期的周一或周日的一个方法,那么这句如何运作的呢?

 

%w 是以数字的形式来表示周中的天数( 0 = Sunday, 1=Monday, . . ., 6=Saturday),0为周日,6为周六,跟我们一般的认知,一周是从周一开始的并不一样。

 

date_format是一个日期转换函数

 

date_format(curdate(),'%w')表示当前日期到上周周日共有几天的间隔,即当前日期减去上周周日的日期=天数(例:curdate()为2011-01-11,那么上周周日为2011-01-09,两者相减为2)所以若单独输出这一句:select date_format(curdate(),'%w') 结果就是2

 

在mysql api里对于subdate函数是这样解释的:

SELECT SUBDATE(NOW( ), 1) AS 'Yesterday',

SUBDATE(NOW( ), INTERVAL -1 DAY) AS 'Tomorrow';

正值为昨天,负值为明天,当前时间的起点,就是当前时间的上周周日

 

subdate函数就是用当前时间减去2天,得到上周周日的时间为2011-01-09

那么如果运行select subdate(curdate(),date_format(curdate(),'%w')-2)这句,就表示用当前时间-(2-2),即-0,得到的结果就是当前日期本身了。

 

如果把%w换成%d呢

%d 是用两位数字来表示月中的天数( 00, 01, . . ., 31)

直接输出的结果就应该是11,表示当前日期在一个月内是第几天

select date_format('2011-01-11','%d')

放到开始的语句里就表示用当前时间减去11,结果为2010-12-31

select subdate('2011-01-11',date_format('2011-01-11','%d'))

 

更多关于data_format的用法可以参考

原文地址:http://musicmmm.iteye.com/blog/868640

 http://www.phpzixue.cn/detail449.shtml

 

/*今天*/
select * from 表名 where to_days(时间字段) = to_days(now());
/*昨天*/
select * from 表名 where to_days(now())-to_days(时间字段) = 1;
/*近7天*/
select * from 表名 where date_sub(curdate(), interval 7 day) <= date(时间字段);
/*查询距离当前现在6个月的数据*/
select * from 表名 where 时间字段 between date_sub(now(),interval 6 month) and now();
/*查询当前这周的数据*/
select * from 表名 where yearweek(date_format(时间字段,'%Y-%m-%d')) = yearweek(now());
/*查询上周的数据*/
select * from 表名 where yearweek(date_format(时间字段,'%Y-%m-%d')) = yearweek(now())-1;
/*查询当前月份的数据*/
select * from 表名 where date_format(时间字段,'%Y-%m')=date_format(now(),'%Y-%m');
/*查询上个月的数据*/
select * from 表名 where date_format(时间字段,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m'); 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics