我有一张表如下:
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 |
感谢任何帮助,谢谢!
答案 0 :(得分:1)
这样的事情应该有效。
SELECT l2.start,l.end 来自student_lectures l LEFT JOIN student_lectures l2 ON l2.end 在l.start和l.end之间 在哪里。开始 BETWEEN'2010-04-26 00:00:00'和'2010-04-26 23:59:59' GROUP BY l.start ORDER BY l.start
答案 1 :(得分:0)
ax
提出了迄今为止我见过的最佳答案 - 即http://explainextended.com/2009/06/13/flattening-timespans-mysql/