使用mysql获取两个日期之间的中间日期

时间:2012-07-07 12:58:22

标签: mysql

获取一组日期之间的错过日期。我希望从日期到日期之间错过日期。我是mysql的新手,请帮助我错过日期之间的日期。

2 个答案:

答案 0 :(得分:0)

这里有类似的内容:Get a list of dates between two dates

答案 1 :(得分:0)

paxdiabloanswer referenced above的答案被{{3}}完全扯掉了。

我所做的就是添加一些测试数据和一个使用左外连接查找缺失日期的示例查询。我在您的评论中使用了测试数据,即

  

"假设我的表有01-01-2012,01-02-2012,01-04-2012,01-05-2012和   01-07-2012。现在我想获得01-03-2012和01-06-2012。我怎样才能得到   这"

您必须找到一种填充all_dates表的方法。它有点取决于什么构成一整套日期'为了你。未来的每一个日期?未来每个月的第一天?过去和未来的每一个日期?过去和未来的每个月的第一天?在这里由你决定。我用2012年每个月的第一天作为例子:

create table all_dates
(id int unsigned not null primary key auto_increment,
a_date date not null,
unique key `all_dates_uidx1`(a_date));

-- First day of every month in 2012    
insert into all_dates (a_date) values ('2012-01-01');
insert into all_dates (a_date) values ('2012-02-01');
insert into all_dates (a_date) values ('2012-03-01');
insert into all_dates (a_date) values ('2012-04-01');
insert into all_dates (a_date) values ('2012-05-01');
insert into all_dates (a_date) values ('2012-06-01');
insert into all_dates (a_date) values ('2012-07-01');
insert into all_dates (a_date) values ('2012-08-01');
insert into all_dates (a_date) values ('2012-09-01');
insert into all_dates (a_date) values ('2012-10-01');
insert into all_dates (a_date) values ('2012-11-01');
insert into all_dates (a_date) values ('2012-12-01');

-- Note that my_dates table is missing 2012-03-01 and 2012-06-01
create table my_dates
(id int unsigned not null primary key auto_increment,
a_date date not null);

insert into my_dates (a_date) values ('2012-01-01');
insert into my_dates (a_date) values ('2012-02-01');
insert into my_dates (a_date) values ('2012-04-01');
insert into my_dates (a_date) values ('2012-05-01');
insert into my_dates (a_date) values ('2012-07-01');
insert into my_dates (a_date) values ('2012-08-01');
insert into my_dates (a_date) values ('2012-09-01');
insert into my_dates (a_date) values ('2012-10-01');
insert into my_dates (a_date) values ('2012-11-01');
insert into my_dates (a_date) values ('2012-12-01');

-- Get me the dates in all_dates that are not present in my_dates 
-- i.e. missing dates
select ad.a_date
from all_dates ad
left join my_dates md on ad.a_date = md.a_date
where md.a_date is null;