在我的 events 表中,有一些每日标志的记录,表明每天必须重复此事件:
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)
通常我会使用一个包含每个日期的表格 实施例
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