MYSQL数据库mysql查询今天、昨天、近7天、近30天、本月、上一月
《MYSQL数据库mysql查询今天、昨天、近7天、近30天、本月、上一月的SQL语句》要点: MYSQL实例mysql查询今天,昨天,近7天,近30天,本月,上一月数据的方法分析总结: select * from `article` where date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d'); MYSQL实例又或: select * from `article` where to_days(date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d')) = to_days(now()); 假设以上表的add_time字段的存储类型是DATETIME类型或者TIMESTAMP类型,则查询语句也可按如下写法: 查询本日的信息记录: 代码如下: select * from `article` where to_days(`add_time`) = to_days(now()); 查询昨天的信息记录: 代码如下: select * from `article` where to_days(now()) C to_days(`add_time`) <= 1; 查询近7天的信息记录: 代码如下: select * from `article` where date_sub(curdate(),INTERVAL 7 DAY) <= date(`add_time`); 查询近30天的信息记录: 代码如下: select * from `article` where date_sub(curdate(),INTERVAL 30 DAY) <= date(`add_time`); 查询本月的信息记录: 代码如下: select * from `article` where date_format(`add_time`,‘%Y%m') = date_format(curdate(),‘%Y%m'); 查询上一月的信息记录: 代码如下: select * from `article` where period_diff(date_format(now(),‘%Y%m'),date_format(`add_time`,‘%Y%m')) =1; 对上面的SQL语句中的几个函数做一下分析: (1)to_days 就像它的名字一样,它是将具体的某一个日期或时间字符串转换到某一天所对应的unix时间戳,如: 代码如下: mysql> select? to_days('2010-11-22 14:39:51');????? ?+--------------------------------+??????????????????????????????????????????????????????? | to_days('2010-11-22 14:39:51') | +--------------------------------+ |???????????????????????? 734463 | +--------------------------------+ MYSQL实例mysql> select? to_days('2010-11-23 14:39:51'); MYSQL实例可以看出22日与23日的差别就是,转换之后的数增加了1,这个粒度的查询是比较粗糙的,有时可能不能满足我们的查询要求,那么就需要使用细粒度的查询办法str_to_date函数了,下面将分析这个函数的用法. MYSQL实例提醒: mysql> select to_days('1997-10-07'),to_days('97-10-07'); ??? -> 729669,729669 MYSQL实例(2)str_to_date mysql> select str_to_date("2010-11-23 14:39:51",'%Y-%m-%d %H:%i:%s'); ? +--------------------------------------------------------+ | str_to_date("2010-11-23 14:39:51",'%Y-%m-%d %H:%i:%s') | +--------------------------------------------------------+ | 2010-11-23 14:39:51??????????????????????????????????? | +--------------------------------------------------------+ MYSQL实例 select str_to_date(article.`add_time`,'%Y-%m-%d %H:%i:%s') from article where str_to_date(article.`add_time`,'%Y-%m-%d %H:%i:%s')>='2012-06-28 08:00:00' and str_to_date(article.`add_time`,'%Y-%m-%d %H:%i:%s')<='2012-06-28 09:59:59'; 欢迎参与《MYSQL数据库mysql查询今天、昨天、近7天、近30天、本月、上一月的SQL语句》讨论,分享您的想法,编程之家PHP学院为您提供专业教程。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |