我正在尝试决定将事件时间存储在 MySQL 数据库中的最佳方式。这些应该尽可能灵活,并且能够表示“单个事件”(从某个时间开始,不一定需要结束时间)、“全天”和“多天”事件、重复事件、重复全天事件,可能是“每月第三个星期六”类型的事件等。
请提出一些久经考验的数据库方案。
Table: Events
This might help. It would require a decent amount of code to interpret when the repeats are. Parts of the time fields that are at lower resolutions than the repeat unit would have to be ignored. Doing the 3rd saturday of the month woudln't be easy either... the NthDayOfMonth info would be required just for doing this kind of functionality.
The database schema required for this is simple in comparison with the code required to work out where repeats fall.
我开发了一个大致遵循 iCalendar 标准(用于记录事件)的计划器应用程序。您可能需要阅读RFC 2445或 Apple Inc. icalendar 架构发布的此架构,以查看它们是否与问题相关。
我的数据库架构(当时没有考虑定期/全天事件)
event (event_id, # primary key
dtstart,
dtend,
summary,
categories,
class,
priority,
summary,
transp,
created,
calendar_id, # foreign key
status,
organizer_id, # foreign key
comment,
last_modified,
location,
uid);
上表中的外键calendar_id
指的是这个
calendar(calendar_id, # primary key
name);
whileorganizer_id
指的是这个(缺少其他属性,如公用名等)
organizer(organizer_id, # primary key
name);
另一个您可能会发现更具可读性的文档位于此处
希望这可以帮助
You need two tables. One for storing the repeating events (table repeatevent) and one for storing the events (table event). Simple entries are only stored in the event table. Repeating entries are stored in the repeatevent table and all single entries for the repeating event are also stored in the event table. This means that everytime you enter a repeating entry, you have to enter all the single resulting entries. You can do this by using triggers, or as part of your business logic.
The advantage of this approach is, that querying events is simple. They are all in the event table. Without the storage of repeating events in the event table, you would have complex SQL or business logic that would make your system slow.
create table repeatevent (
id int not null auto_increment,
type int, // 0: daily, 1:weekly, 2: monthly, ....
starttime datetime not null, // starttime of the first event of the repetition
endtime datetime, // endtime of the first event of the repetition
allday int, // 0: no, 1: yes
until datetime, // endtime of the last event of the repetition
description varchar(30)
)
create table event (
id int not null auto_increment,
repeatevent null references repeatevent, // filled if created as part of a repeating event
starttime datetime not null,
endtime datetime,
allday int,
description varchar(30)
)
Same way the cron does it? Recording both start and end time that way.
使用 datetime 和 mysql 内置的 NOW() 函数。在流程开始时创建记录,在流程结束时更新跟踪结束时间的列。