鉴于我有表格(events
),其他人包含列date
,reoccur
和frequency
其中reoccur
可能是enum
:'d'
,'w'
或y
,持续数天,数周或数年
+---------------------+-----------+-------------+
| eventdate | reoccur | frequency |
+---------------------+-----------+-------------+
| 2014-03-31 00:00:00 | w | 4 |
| 2014-07-01 00:00:00 | d | 7 |
+---------------------+-----------+-------------+
如何在选定年份内为每个重复发生的事件选择一行?
我认为我需要一个mysql while循环才能实现这个目的?我已经研究了一段时间的可能性,我仍然坚持从哪里开始
答案 0 :(得分:1)
我想这可以用MySQL完成,但我认为我更喜欢应用程序级方法,如下所示。注意,在PHP方面我不是专家,为了简单和清晰(并且可能以一些灵活性为代价),我稍微修改了你的设计......
的DDL:
CREATE TABLE events
(event_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,event_date DATE NOT NULL
,recurrence_pattern ENUM('day','week','month','year') NULL
,no_of_occurrences INT NULL
);
INSERT INTO events VALUES
(1,'2014-03-31 00:00:00','week',4),
(2,'2014-07-01 00:00:00','day',7);
PHP:
<?php
include('path/to/connection/stateme.nts');
$query = "
SELECT event_id
, event_date
, recurrence_pattern
, no_of_occurrences
FROM events
ORDER
BY event_date;
";
$result = mysqli_query($db,$query);
while($row = mysqli_fetch_assoc($result)){
for($i=0;$i<$row['no_of_occurrences'];$i++){
echo date('Y-m-d',strtotime("{$row['event_date']} + $i {$row['recurrence_pattern']}")), "\n";
}
}
?>
输出:
2014-03-31
2014-04-07
2014-04-14
2014-04-21
2014-07-01
2014-07-02
2014-07-03
2014-07-04
2014-07-05
2014-07-06
2014-07-07