发布于 2016-03-16 23:48:23 | 203 次阅读 | 评论: 0 | 来源: 网友投递
Mysql关系型数据库管理系统
MySQL是一个开放源码的小型关联式数据库管理系统,开发者为瑞典MySQL AB公司。MySQL被广泛地应用在Internet上的中小型网站中。由于其体积小、速度快、总体拥有成本低,尤其是开放源码这一特点,许多中小型网站为了降低网站总体拥有成本而选择了MySQL作为网站数据库。
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 to_days(date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d')) = 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;
select * from `article` where date_sub(curdate(), INTERVAL 7 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 period_diff(date_format(now() , ‘%Y%m') , date_format(`add_time`, ‘%Y%m')) =1;
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-23 14:39:51');
+--------------------------------+
| to_days('2010-11-23 14:39:51') |
+--------------------------------+
| 734464 |
+--------------------------------+
可以看出22日与23日的差别就是,转换之后的数增加了1,这个粒度的查询是比较粗糙的,有时可能不能满足我们的查询要求,那么就需要使用细粒度的查询方法str_to_date函数了,下面将分析这个函数的用法。
提醒:
(1)to_days() 不用于阳历出现(1582)前的值,原因是当日历改变时,遗失的日期不会被考虑在内。因此对于1582 年之前的日期(或许在其它地区为下一年 ), 该函数的结果实不可靠的。
(2)MySQL"日期和时间类型"中的规则是将日期中的二位数年份值转化为四位。因此对于'1997-10-07'和'97-10-07'将被视为同样的日期:
mysql> select to_days('1997-10-07'), to_days('97-10-07');
-> 729669, 729669
(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 |
+--------------------------------------------------------+
具体案例操作如下:
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';