In the picture I have this setup where I subtract the different datetime field of the next column. I have it done, but it slows down to the point that it time-out at 200k records. Please help me optimize my SQL query.
SELECT barcode,documents.document_title, routes.receive_at, routes.release_at,
SEC_TO_TIME(
SUM(
TIME_TO_SEC(
timediff(
receive_at, (SELECT
release_at
FROM
routes table12
WHERE DATE(routes.receive_at) between "2021-10-01" AND "2021-10-18" and routes.id < table12.id
ORDER BY
id ASC
LIMIT 1
)
)
)
)
) as time_office,
SEC_TO_TIME(
SUM(
TIME_TO_SEC(
timediff(
receive_at, routes.release_at
)
)
)
) as time_travel
from routes
LEFT JOIN documents on routes.barcode = documents.document_code
WHERE DATE(routes.receive_at) between "2021-10-01" AND "2021-10-18"
order by routes.id ASC