Prøv denne forespørgsel
SELECT
a.id,
a.start_hour,
a.end_hour,
TIMEDIFF(la.start_hour, a.end_hour) as `Free Time`
FROM appointment as a
LEFT JOIN(SELECT * FROM appointment LIMIT 1,18446744073709551615) AS la
ON la.id = a.id + 1
LEFT JOIN (SELECT * FROM appointment) AS ra ON a.id = ra.id
Dette vil vise disse resultater
+---------------------------------------------+
¦ id ¦ start_hour BY ¦ end_hour | Free Time |
¦----+---------------¦------------------------|
¦ 1 ¦ 08:00:00 ¦ 08:15:00 | 05:45:00 |
¦ 2 ¦ 14:00:00 ¦ 14:30:00 | 02:30:00 |
¦ 3 ¦ 17:00:00 ¦ 17:45:00 | 03:15:00 |
¦ 4 ¦ 21:00:00 ¦ 21:00:00 | (NULL) |
+--------------------+------------------------+
Du skal også have 21:00:00 i tabellen, ellers vil du ikke være i stand til at få den sidste tidsforskel. jeg indtastede 21:00:00 som start- og slutdato i tabellen.
REDIGERET
Dette er ændret forespørgsel
SELECT
a.id,
a.end_hour AS `Free time Start`,
IFNULL(la.start_hour,a.end_hour) AS `Free Time End`,
IFNULL(TIMEDIFF(la.start_hour, a.end_hour),'00:00:00') AS `Total Free Time`
FROM appointment AS a
LEFT JOIN (SELECT * FROM appointment LIMIT 1,18446744073709551615) AS la
ON la.id = (SELECT MIN(id) FROM appointment where id > a.id LIMIT 1)
Og resultatet er
+--------------------------------------------------------+
¦ id ¦ Free time Start ¦ Free Time End | Total Free Time |
¦----+-----------------¦---------------------------------|
¦ 1 ¦ 08:15:00 ¦ 14:00:00 | 05:45:00 |
¦ 2 ¦ 14:30:00 ¦ 17:00:00 | 02:30:00 |
¦ 3 ¦ 17:45:00 ¦ 21:00:00 | 03:15:00 |
¦ 4 ¦ 21:00:00 ¦ 21:00:00 | 00:00:00 |
+----------------------+---------------------------------+
Punkterne at lære af denne forespørgsel er
- Timediff-funktionsbrug. timediff('sluttidspunkt','starttidspunkt')
- Tilslutning med øverste nummer
- Undgå første rekord i join med en lang offset og grænse startende fra 1 i stedet for nul
- IFNULL-brug ifnull('hvis her kommer null','vælg dette derefter')