我有一个选择泰铢带来这样的结果:
+-----------+------------+--------------+
| parking_id| start_time | end_time |
+-----------+------------+--------------+
| 38 | 09:15:00 | 10:32:00 |
| 57 | 11:45:00 | 13:21:00 |
| 33 | 14:40:00 | 16:35:00 |
| 15 | 17:13:00 | 19:15:00 |
| 68 | 20:54:00 | NULL |
+-----------+------------+--------------+
如您所见,ID并不遵循线性顺序,但是我真正需要的是一个选择,它为我带来了最后插入的新start_time和end_time之间的时间,它遵循此非线性顺序,因此我需要一个选择使我这个:
+-----------+------------+--------------+----------------+
| parking_id| start_time | end_time | time_btw_parks |
+-----------+------------+--------------+----------------+
| 38 | 09:15:00 | 10:32:00 | NULL |
| 57 | 11:45:00 | 13:21:00 | 01:13:00 |
| 33 | 14:40:00 | 16:35:00 | 01:19:00 |
| 15 | 17:13:00 | 19:15:00 | 00:38:00 |
| 68 | 20:54:00 | NULL | 01:39:00 |
+-----------+------------+--------------+----------------+
不一定非要选择查询。任何解决它的方法都会有所帮助。
最佳答案
对于此样本数据,可以使用timediff()
函数:
select t.parking_id, t.start_time, t.end_time,
timediff(t.start_time, max(tt.end_time)) time_btw_parks
from tablename t left join tablename tt
on t.start_time > tt.end_time
group by t.parking_id, t.start_time, t.end_time
order by t.start_time
请参见demo。
结果:
| parking_id | start_time | end_time | time_btw_parks |
| ---------- | ---------- | -------- | -------------- |
| 38 | 09:15:00 | 10:32:00 | |
| 57 | 11:45:00 | 13:21:00 | 01:13:00 |
| 33 | 14:40:00 | 16:35:00 | 01:19:00 |
| 15 | 17:13:00 | 19:15:00 | 00:38:00 |
| 68 | 20:54:00 | | 01:39:00 |
关于mysql - MYSQL-如何在同一张表的两个不同行上减去两列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60021642/