一些变量说明:
add_time为插入的时间
to_days是sql函数,返回的是个天数 (注意:对时间戳无效,仅对如 2018-08-03格式日期有效)
data_sub(date,INTERVAL expr type)给指定的日期减去多少天
data()函数返回日期或日期/时间表达式的日期部分。
curdate()函数返回当前的日期 y-m-d
data_format 用于以不同的格式显示日期/时间数据(注意:不能是时间戳)
period_diff(p1,p2)返回周期P1和P2之间的月数。 P1和P2格式为YYMM或YYYYMM。注意周期参数 P1 和 P2 都不是日期值
unix_timestamp() 时间转时间戳方法
from_unixtime() 时间戳转时间的方法
1、查询今天的所有记录:
(1)add_time字段,该字段为int(5)类型的
select * from `article` where to_days(date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d')) = to_days(now());
(2)add_time字段是DATETIME类型或者TIMESTAMP类型的
select * from `article` where to_days(`add_time`) = to_days(now());
2、查询昨天的所有记录
select * from `article` where to_days(now()) <= 1 + to_days(`add_time`);
3、近7天的信息记录:
select * from `article` where date_sub(curdate(), INTERVAL 7 DAY) <= date(`add_time`);
4、近30天的信息记录:
select * from `article` where date_sub(curdate(), INTERVAL 30 DAY) <= date(`add_time`);
5、查询本月的记录
select * from `article` where date_format(`add_time`, ‘%Y%m') = date_format(curdate() , ‘%Y%m');
6、上一个月的记录
select * from `article` where period_diff(date_format(now() , ‘%Y%m') , date_format(`add_time`, ‘%Y%m')) =1;
8、下面是在thinkphp上的使用
查询最近7天的记录
原生sql :
select * from p_log_days_earn where add_time between unix_timestamp(date_sub(curdate(),interval 7 day)) AND unix_timestamp(date(now())) ADN user_id=1 order by id desc;
thinkphp用法 :
$where['add_time'] = array('exp',"BETWEEN unix_timestamp(date_sub(curdate(),interval 7 day)) AND unix_timestamp(now())");
查询最近一个月30天的记录
原生sql :
select * from p_log_days_earn where add_time between unix_timestamp(date_sub(curdate(),interval 30 day)) AND unix_timestamp(date(now())) AND user_id=1 order by id desc;
thinkphp用法 :
$where['add_time'] = array('exp',"BETWEEN unix_timestamp(date_sub(curdate(),interval 30 day)) and unix_timestamp(now())");
9、统计最近7天每天多少条数据,按日期分组然后统计
原生sql :
SELECT count(user_id),FROM_UNIXTIME(follow_time) AS time FROM `p_orders_followed` WHERE `follow_time` BETWEEN UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) AND UNIX_TIMESTAMP(NOW()) AND `user_id` = 1 GROUP BY to_days(time);
thinkphp用法 :
$where['follow_time'] = array('exp','BETWEEN UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) AND UNIX_TIMESTAMP(NOW())');
$where['user_id'] = $params['user_id'];
$res = $this
->field('COUNT(user_id) AS total,FROM_UNIXTIME(follow_time,"%Y-%m-%d") AS time')
->where($where)
->group('to_days(time)') // 注意:此处的time是FROM_UNIXTIME(follow_time,"%Y-%m-%d") AS time的别名,且to_days里最好使用别名,且不能跟表的字段名一样,否则会出异常
->select();
注意:此处的time是FROM_UNIXTIME(follow_time,"%Y-%m-%d") AS time的别名,且to_days里最好使用别名,且不能跟表的字段名一样,否则会出异常
网友评论