我有一张桌子如下:
mysql> DESCRIBE student_lectures;
+------------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| course_module_id | int(11) | YES | MUL | NULL | |
| day | int(11) | YES | | NULL | |
| start | datetime | YES | | NULL | |
| end | datetime | YES | | NULL | |
| cancelled_at | datetime | YES | | NULL | |
| lecture_type_id | int(11) | YES | | NULL | |
| lecture_id | int(11) | YES | | NULL | |
| student_id | int(11) | YES | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+------------------+----------+------+-----+---------+----------------+
我本质上是想找出没有发生讲座的时间-为此,我正在考虑将重叠的讲座分组在一起的查询(例如,上午 9 点至上午 10 点和上午 10 点至 11 点的讲座将显示为上午 9 点至 11 点的单人讲座)。背靠背可能有两个以上的讲座。
我目前有这个:
SELECT l.start, l2.end
FROM student_lectures l
LEFT JOIN student_lectures l2 ON ( l2.start = l.end )
WHERE l.student_id = 1 AND l.start >= '2010-04-26 09:00:00' AND l.end <= '2010-04-30 19:00:00' AND l2.end IS NOT NULL AND l2.end != l.start
GROUP BY l.start, l2.end
ORDER BY l.start, l2.start
返回:
+---------------------+---------------------+
| start | end |
+---------------------+---------------------+
| 2010-04-26 09:00:00 | 2010-04-26 11:00:00 |
| 2010-04-26 10:00:00 | 2010-04-26 12:00:00 |
| 2010-04-26 10:00:00 | 2010-04-26 13:00:00 |
| 2010-04-26 13:15:00 | 2010-04-26 16:15:00 |
| 2010-04-26 14:15:00 | 2010-04-26 16:15:00 |
| 2010-04-26 15:15:00 | 2010-04-26 17:15:00 |
| 2010-04-26 16:15:00 | 2010-04-26 18:15:00 |
...etc...
我正在寻找的输出将是:
+---------------------+---------------------+
| start | end |
+---------------------+---------------------+
| 2010-04-26 09:00:00 | 2010-04-26 13:00:00 |
| 2010-04-26 13:15:00 | 2010-04-26 18:15:00 |
任何帮助表示赞赏,谢谢!