我不确定这张表的主键是什么。我相当有信心我的错误对您来说是错误的,但这对于您提出问题的目的并不重要。
-- student_id and class_id are foreign keys, not shown
create table times (
student_id integer not null,
class_id integer not null,
primary key (student_id, class_id),
start_time timestamp not null,
end_time timestamp not null
);
第一个学生在第 2 班和第 3 班之间有重叠。
insert into times values
(1, 1, '2012-09-01 08:00', '2012-09-01 08:55'),
(1, 2, '2012-09-01 10:00', '2012-09-01 11:55'),
(1, 3, '2012-09-01 11:45', '2012-09-01 12:45');
第二个学生,没有重叠。
insert into times values
(2, 1, '2012-09-01 08:00', '2012-09-01 08:55'),
(2, 2, '2012-09-01 10:00', '2012-09-01 11:55');
第三个学生在第 1 班和第 2 班之间有重叠。
insert into times values
(3, 1, '2012-09-01 08:00', '2012-09-01 10:00'),
(3, 2, '2012-09-01 09:55', '2012-09-01 11:55'),
(3, 3, '2012-09-01 12:00', '2012-09-01 12:55');
如果您的平台符合 SQL-92,则可以使用 OVERLAPS 运算符。(如果任何 dbms 支持断言,您可以以无法插入重叠类的方式声明表。)
select t1.*
from times t1
inner join times t2 on t1.student_id = t2.student_id
and (t1.class_id <> t2.class_id and t1.start_time <> t2.start_time and t1.end_time <> t2.end_time )
and (t1.start_time, t1.end_time) overlaps (t2.start_time, t2.end_time);
MySQL 似乎不支持这一点,因此您可以使用 SQL 标准委员会的等效定义。
select t1.*
from times t1
inner join times t2 on t1.student_id = t2.student_id
and (t1.class_id <> t2.class_id and t1.start_time <> t2.start_time and t1.end_time <> t2.end_time )
and (
(t1.start_time > t2.start_time and not (t1.start_time >= t2.end_time and t1.end_time >= t2.end_time))
or
(t2.start_time > t1.start_time and not (t2.start_time >= t1.end_time and t2.end_time >= t1.end_time))
or
(t1.start_time = t2.start_time and (t1.end_time <> t2.end_time or t1.end_time = t2.end_time))
);
我希望连接条件能够为您提供良好的性能,只要您的表被仔细索引。在您的情况下,您将为单个学生选择行,这应该是非常有选择性的。(我的示例代码中没有这样做。)