为了清楚起见,一个字段中不能有 2 个引用,所以我使用一个表来保存交叉引用......即 daily_tasks,您可以在一天中的每个时间段插入任意数量的项目,唯一的限制是您不能在一个时间段内两次执行相同的任务,但即使删除主键声明也可以删除
create table task(
id tinyint unsigned not null auto_increment primary key,
name text not null
) engine InnoDB;
create table timeslot(
id int unsigned not null auto_increment primary key,
date date not null,
time tinyint unsigned not null
) engine InnoDB;
create table daily_tasks(
timeslot int unsigned not null,
task tinyint unsigned not null,
foreign key(timeslot) references timeslot(id) on update cascade on delete cascade,
foreign key(task) references task(id) on update cascade on delete cascade,
primary key(timeslot,task)
) engine InnoDB;
插入一些样本数据
insert into task (name) values ('wake up'), ('wash'), ('eat'), ('drink'), ('go to work'), ('do some work');
insert into timeslot (date, time) values ('2012-09-18', 8), ('2012-09-18', 11), ('2012-09-18', 14), ('2012-09-18', 17), ('2012-09-18', 20);
insert into daily_tasks values (1, 1), (1,3), (1,4), (1,5), (2,6), (3,6), (4,3), (4,4), (4,2);
选择一天的所有任务
select timeslot.time, task.name from timeslot join daily_tasks on daily_tasks.timeslot = timeslot.id join task on task.id = daily_tasks.task where timeslot.date = '2012-09-18' order by timeslot.time asc;
查询结果
+------+--------------+
| time | name |
+------+--------------+
| 8 | wake up |
| 8 | eat |
| 8 | drink |
| 8 | go to work |
| 11 | do some work |
| 14 | do some work |
| 17 | wash |
| 17 | eat |
| 17 | drink |
+------+--------------+
9 rows in set (0.00 sec)
具有串联任务的替代查询
select timeslot.time, group_concat(task.name) from timeslot join daily_tasks on daily_tasks.timeslot = timeslot.id join task on task.id = daily_tasks.task where timeslot.date = '2012-09-18' group by timeslot.time asc;
导致
+------+------------------------------+
| time | group_concat(task.name) |
+------+------------------------------+
| 8 | wake up,eat,drink,go to work |
| 11 | do some work |
| 14 | do some work |
| 17 | wash,eat,drink |
+------+------------------------------+
4 rows in set (0.01 sec)
因为显然所有间隔都是 3 小时长我没有包括任务的结束时间,因为这可以通过将 3 添加到时间来计算