DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`raidUpdate`() BEGIN UPDATE Entradas e JOIN Entradas_Auto ea USING (Id_Entrada) JOIN travel t ON t.id = e.travel_id JOIN ( SELECT * FROM ( SELECT id, landing, warehouse_id, warehouse_id_out FROM travel JOIN ( SELECT warehouse_id, warehouse_id_out FROM Entradas_Auto ea JOIN Entradas e USING(Id_Entrada) JOIN travel t ON t.id = e.travel_id GROUP BY warehouse_id, warehouse_id_out ) t USING (warehouse_id, warehouse_id_out) WHERE shipment > util.VN_CURDATE() AND delivered = FALSE ORDER BY landing LIMIT 10000000000000000000 ) t GROUP BY warehouse_id, warehouse_id_out ) t USING (warehouse_id, warehouse_id_out) SET e.travel_id = t.id; END$$ DELIMITER ;