mysql 第3.6章 查询-时间 mysql 第3.6章 查询-时间

2小时前

一、内置时间函数

current_date()/curdate() 当天日期,2018-07-09
current_time()/curtime() 当前时间,11:50:59
sysdate() 执行到当前函数时的时间,2018-07-09 11:50:59
current_timestamp()/now() 执行SQL语句时的时间,2018-07-09 11:50:59
SELECT now(),current_timestamp(),sysdate(),sleep(2),now(),current_timestamp(),sysdate()
结果会发现最后一个SYSDATE()显示的时间会较其他时间大两秒。
unix_timestamp() 日期转时间戳
from_unixtime() 时间戳转日期
to_days() 函数返回一个天数! 从年份0开始的天数
有一张表!order表 有一个字段 create_time  类型 datetime  
如果要查询当前表中昨天的数据那么
select * from order where to_days(now())-to_days(create_time)<1
from_days()给出一个天数 N,返回一个 DATE 值
date_sub(date,INTERVAL expr type) 函数从日期减去指定的时间间隔。
select date_sub(curdate(),interval 7 day)
date() 函数返回日期或日期/时间表达式的日期部分。
year(date)返回日期的年份,范围为1000到9999,或者对于“零”日期返回0。
quarter(date)返回日期的一年中的季度,范围为1到4。
month(date)返回日期的月份,1月至12月的范围为1至12,对于包含月份为零的日期(如“0000-00-00”或“2008-00-00”),返回0。
week(date[,mode])此函数返回日期的周号。 week()的双参数使您能够指定星期是从星期天还是星期一开始,以及返回值是在0到53还是从1到53的范围内。如果省略mode参数,则值 使用了default_week_format系统变量。
yearweek 是获取年份和周数的一个函数
cast函数语法规则是:cast(字段名 as 转换的类型 ),其中类型可以为:
char[(N)] 字符型 、date 日期型、datetime 日期和时间型、decimal float型、signed int、time 时间型
period_diff() 返回两个时段之间的月份差值

二、案例

今天: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(时间字段名)
近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 * from 表名 where quarter(时间字段名) = quarter(now())
查询上季度数据:select * from 表名 where quarter(时间字段名) = quarter(date_sub(now(),interval 1 quarter))
查询本年数据:select * from 表名 where year(时间字段名) = year(now())
查询上年数据:select * from 表名 where year(时间字段名) = year(date_sub(now(),interval 1 year))
查询当前这周的数据:select * from 表名 where yearweek(date_format(时间字段名,'%Y-%m-%d')) = yearweek(now())
查询上周的数据:select * from 表名 where yearweek(date_format(时间字段名,'%Y-%m-%d')) = yearweek(now())-1
阅读 5

mysql文章
带到手机上看