mysql日期查询操作

来源:互联网 发布:axure 8.0mac安装教程 编辑:程序博客网 时间:2024/06/06 09:54
今天
select * from 表名 where to_days(时间字段名) = to_days(now());
昨天
Select * FROM 表名 Where TO_DAYS( NOW( ) ) – TO_DAYS( 时间字段名) <= 1
7天前 如果是7天后就是DATE_ADD函数
Select * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(时间字段名)
近30天前
Select * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(时间字段名)
本月
Select * FROM 表名 Where DATE_FORMAT( 时间字段名, ‘%Y%m’ ) = DATE_FORMAT( CURDATE( ) , ‘%Y%m’ )
上一月
Select * FROM 表名 Where PERIOD_DIFF( date_format( now( ) , ‘%Y%m’ ) , date_format( 时间字段名, ‘%Y%m’ ) ) =1
//时间转成年月日时分秒
select date_format(now(),'%Y%m%d%H%i%S')
//时间转成年月日
select date_format(now(),'%Y%m%d')
//去年此时
select DATE_ADD(now(), Interval -1 year)
//上月此时
select DATE_ADD(now(), Interval -1 month)
//昨天此时
select DATE_ADD(now(), Interval -1 day)
//一小时前
select DATE_ADD(now(), Interval -1 hour)
//一分钟前
select DATE_ADD(now(), Interval -1 minute)
//一秒钟前
select DATE_ADD(now(), Interval -1 second)
//昨天(年月日)
select date_format(DATE_ADD(now(), Interval 1 day),'%Y%m%d')
//上个月第一天和最后一天
select date_sub(date_sub(date_format(now(),'%Y%m%d'),interval extract( day from now())-1 day),interval 1 month);
select date_sub(date_sub(date_format(now(),'%Y%m%d'),interval extract(day from now()) day),interval 0 month);
  
//某个字符串
select date_format(DATE_ADD('20090605123020', Interval 20 minute),'%Y%m%d')
//第几周
select weekofyear( now() )
select weekofyear('20090606')
在mysql中,会把'20090707123050'和'20090707'格式的字符串作为date类型转换。
 
在mysql中,没有类似oracle的to_char(num,format)函数,所以涉及到数字前面补0的情况需要特殊处理。
如select left(concat('00'),@num),3)就会显示三位数字的字符串, @num=1时显示001,为123是显示123。
CONCAT(YEAR(a.createtime),LEFT(CONCAT('0',WEEKOFYEAR(a.createtime)),2))
还有FROM_UNIXTIME 这个可以数字转日期
0 0