MySQL SELECT用于迭代日期

时间:2015-11-09 09:40:02

标签: php mysql iteration

我有这个MySql表(简化):

tbl_cards
ID  FROM        TO
--------------------------
 1  2015-10-01  2015-10-08
 2  2015-10-06  2015-10-12
 3  2015-10-06  2015-10-15
 4  ...

我需要一个SELECT来检查每个日期之间的日期。 2015-10-01和2015-12-31并返回3(或任意数字)ID重叠的日期。有些日期没有任何记录,而其他日期可能有很多。

在上表中,2015-10-06和2015-10-07是"共享"通过3条记录,这意味着那些是我需要返回的日期:

Index  Date
-----------------
 0     2015-10-06
 1     2015-10-07
 2     2015-10-08

我当然可以让我的PHP脚本迭代指定范围内的每个日期并计算每个日期的记录,但我猜测如果可以在MySql中完成整个操作会更快吗?

1 个答案:

答案 0 :(得分:1)

<强>计划

  
      
  • 使用digits_v和date_add创建一个带有一些十进制逻辑的日历数据源(所有数字表示为* 10 ^ n + ... a0 * 10 ^ 0)   编号
  •   
  • 将日历数据加入tbl_cards,条件属于间隔
  •   
  • 聚合超过计数等于3
  •   
  • 使用变量创建索引字段输出
  •   

<强>设置

create table tbl_cards
(
  id integer primary key not null,
  `from` date not null,
  `to` date not null
);

insert into tbl_cards
( id, `from`, `to` )
values
( 1,  '2015-10-01',  '2015-10-08' ),
( 2,  '2015-10-06',  '2015-10-12' ),
( 3,  '2015-10-06',  '2015-10-15' )
;

drop view if exists digits_v;
create view digits_v
as
select 0 as n
union all
select 1 union all select 2 union all select 3 union all 
select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9
;

<强>查询

select @index := @index + 1 as `Index`, `Date`
from
(
  select date_format(calendar.dy, '%Y-%m-%d') as `Date`
  from
  (
    select date_add(date('2015-10-01'), interval a2.n * 100 + a1.n * 10 + a0.n day) as dy
    from digits_v a2
    cross join digits_v a1
    cross join digits_v a0
    where date_add('2015-10-01', interval a2.n * 100 + a1.n * 10 + a0.n day) 
    <=    date('2015-12-31')
    order by date_add('2015-10-01', interval a2.n * 100 + a1.n * 10 + a0.n day)
  ) calendar
  inner join tbl_cards t
  on calendar.dy between t.`from` and t.`to`
  group by calendar.dy
  having count(calendar.dy) = 3
) dts
cross join ( select @index := -1 ) params
;

<强>输出

+-------+------------+
| Index |    Date    |
+-------+------------+
|     0 | 2015-10-06 |
|     1 | 2015-10-07 |
|     2 | 2015-10-08 |
+-------+------------+

<强> sqlfiddle

<强>参考