En la imagen, tengo esta configuración donde resto el campo de fecha y hora diferente de la siguiente columna. Lo tengo hecho, pero se ralentiza hasta el punto de que se agota el tiempo de espera en 200k registros. Por favor, ayúdame a optimizar mi consulta SQL.
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