mysql日期查询操作
/////////////////今天找到了一些比较有用的mysql日期函数,在此做一下记录,以备后期使用///////////////////////
今天
select * from 表名 where to_days(时间字段名) = to_days(now());
昨天
select * from 表名 where to_days( now( ) ) – to_days( 时间字段名)
7天前 如果是7天后就是date_add函数
select * from 表名 where date_sub(curdate(), interval 7 day)
近30天前
select * from 表名 where date_sub(curdate(), interval 30 day)
本月
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 这个可以数字转日期
bitscn.com
