2011-09-12 41 views
1

在我事件表還有一些有每天標誌記錄證明,對這一事件必須重複每天:返回多個副本稍加修改

CREATE TABLE IF NOT EXISTS `events` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `start` datetime DEFAULT NULL, 
    `title` varchar(64) COLLATE utf8_unicode_ci NOT NULL, 
    `description` varchar(64) COLLATE utf8_unicode_ci NOT NULL, 
    `daily` tinyint(1) NOT NULL, 
) ENGINE=InnoDB; 

當我嘗試填補日曆這些數據我需要爲每個項目設置一行,如果日曆要求本週所有事件,則每日觸發事件必須使用相同的數據(標題,描述等)返回7個事件(每週一天),但是用不同的開始一天。

從MySQL可以做到嗎?

+0

我不認爲這是應該做的正確方法.. –

+0

你能解釋一下嗎? – Ivan

回答

0

通常我會使用一個包含每個日期的表。

create table daily 
(
    /* FYI, date is not a reserved keyword */ 
    date date 
); 

insert into daily values ('2011-09-11'), ('2011-09-12'), 
('2011-09-13'), ('2011-09-14'), ('2011-09-15'), 
('2011-09-16'), ('2011-09-17'); 

alter table daily add index (date); 

select daily.date as daily_date, 
     weekly.start, weekly.id, weekly.title, weekly.description 
from daily 
inner join 
(
    select events.id, events.title, 
      events.description, events.start, events.daily 
    from events 
    where events.start between '2011-09-11' and '2011-09-17' 
) as weekly 
on date(weekly.start)=daily.date 
union 
/* query for recurr */ 
select daily.date as daily_date, 
     recurr.start, recurr.id, recurr.title, recurr.description 
from daily 
inner join 
(
    select events.id, events.title, 
      events.description, events.start, events.daily 
    from events 
    where events.daily=1 AND events.start between '2011-09-11' and '2011-09-17' 
)as recurr 
on date(recurr.start)<=daily.date 
order by daily_date; 

,如果你打破了起始列兩列(日期,時間),這將是更有效的。
這種方法的缺點是在表daily的預創建並加載它有很多日價值。

這應該是一次性成本,並且可以通過for輕鬆插入。
或者,你可以做一個重複(從本週開始到週末)在query for recurr