mysql根据int时间_MySQL中根据年月日(int型)查询一段时间内的数据

问题描述:

MySQL数据表以id为主键,存在多列属性值,其中三列属性分别用int型来存储year,month和day。

现在想根据这三列的数据,获得一段时间内的表的数据(从今天往前数五天内的数据)。

其实本可以将年月日等时间信息存放到一个date中,但是根据实际的需求,如果将年月日等时间数据分开存放,可以考虑使用下面的方法。

问题解决:

假设存在一个数据表DateTable,该表中有N多列,M多行数据,id为主键,存在三列int型的数据,分别为year,month,day。

针对原表,创建一个视图view,该视图中只保存两个数据,一个是原表对应的id值,一个是根据原表中的year,month,day生成的date数据

create view v_dateInfo(id,_date) as select id,str_to_date(concat(year,'-',month,'-',day), '%Y-%m-%d‘) from DateTable;

--注释:年月日的格式要写正确了,'%Y-%m-%d‘,第一个是大写,后面都是小写。第一次运行结果返回均为NULL就是因为格式不对。

如上代码就根据表DateTable创建了一个视图v_dateInfo,该视图只有两个数据,一个是id,一个是_date数据值。

接着通过访问视图来获得原表中从今天开始往前数五天的所有数据。代码如下:

select * from DateTable where id in (select id from v_dateInfo where _date between DATE_ADD(NOW(),INTERVAL -5 DAY)  and NOW());

使用到的内置函数:

concat(string1,string2,string3,...,stringN)                                     --将字符串string1,string2,string3,...,stringN连接成一个字符串并返回

str_to_date(string,'%Y-%m-%d‘)                                                  --将字符串string转换为年-月-日的时间格式

DATE_ADD(date,interval n type)                                                 --获得与date间隔为n的date数据,type为时间类型,可以为day,month等

测试用例如下所示:

USE 'home';

--drop table if exists 'date1';

create table date1(

id int(11) primary key auto_increment,

year int(11) not null,

month int(11) not null,

day int(11) not null

);

lock tables 'date1' write;

insert into date1 values

(1,2013,06,20),(2,2013,06,21),(3,2013,06,22),

(4,2013,06,23),(5,2013,06,24),(6,2013,06,25),

(7,2013,06,26),(8,2013,06,27),(9,2013,06,28),

(10,2013,06,29),(11,2013,06,30),(12,2013,07,01),

(13,2013,07,02),(14,2013,07,03),(15,2013,07,04),

(16,2013,07,05),(17,2013,07,06),(18,2013,07,07);

unlock tables;

drop view if exists date_info;

create view date_info(id,da) as select id,str_to_date(concat(year,'-',month,'-',day),'%Y-%m-%d') from date1;

select * from date1 where id in (select id from date_info where da between DATE_ADD(now(),interval -5 day) and now());

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值