本文整理自网络,侵删。
mysql查询今天,昨天,近7天,近30天,本月,上一月数据的方法分析总结:
话说有一文章表article,存储文章的添加文章的时间是add_time字段,该字段为int(5)类型的,现需要查询今天添加的文章总数并且按照时间从大到小排序,则查询语句如下:
代码如下:
select * from `article` where date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d');
select * from `article` where date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d');
或者:
代码如下:
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(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(`add_time`) = to_days(now());
查询昨天的信息记录:
代码如下:
select * from `article` where to_days(now()) – to_days(`add_time`) <= 1;
查询近7天的信息记录:
select * from `article` where to_days(now()) – 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 7 DAY) <= date(`add_time`);
查询近30天的信息记录:
代码如下:
select * from `article` where date_sub(curdate(), INTERVAL 30 DAY) <= date(`add_time`);
查询本月的信息记录:
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 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时间戳,如:
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> select to_days('2010-11-22 14:39:51');
+--------------------------------+
| to_days('2010-11-22 14:39:51') |
+--------------------------------+
| 734463 |
+--------------------------------+
相关阅读 >>
sql2008中sql应用之-锁定(locking) 应用分析
更多相关阅读请进入《sql》频道 >>

数据库系统概念 第6版
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。
相关推荐
评论
管理员已关闭评论功能...
- 欢迎访问木庄网络博客
- 可复制:代码框内的文字。
- 方法:Ctrl+C。