DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`route_getTickets`(vRouteFk INT) BEGIN /** * Pasado un RouteFk devuelve la informaciĆ³n * de sus tickets. * * @param vRouteFk * @select InformaciĆ³n de los tickets */ SELECT t.id Id, t.clientFk Client, a.id Address, a.nickname ClientName, t.packages Packages, a.street AddressName, a.postalCode PostalCode, a.city City, sub3.itemPackingTypeFk PackingType, c.phone ClientPhone, c.mobile ClientMobile, a.phone AddressPhone, a.mobile AddressMobile, d.longitude Longitude, d.latitude Latitude, wm.mediaValue SalePersonPhone, tob.description Note, t.isSigned Signed, t.priority, t.cmrFk FROM ticket t JOIN client c ON t.clientFk = c.id JOIN address a ON t.addressFk = a.id LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk LEFT JOIN ( SELECT t.addressFk, MAX(d.ticketFk) lastTicketFk FROM ticket t JOIN delivery d ON t.id = d.ticketFk JOIN ticket ti ON ti.routeFk = vRouteFk AND ti.id = t.id AND ti.clientFk = t.clientFk GROUP BY addressFk )sub ON sub.addressFk = a.id LEFT JOIN delivery d ON d.ticketFk = sub.lastTicketFk LEFT JOIN( SELECT t.id ticketFk, tob.description FROM ticketObservation tob JOIN ticket t ON tob.ticketFk = t.id JOIN observationType ot ON ot.id = tob.observationTypeFk WHERE t.routeFk = vRouteFk AND ot.code = 'delivery' )tob ON tob.ticketFk = t.id LEFT JOIN( SELECT sub2.ticketFk, CONCAT('(', GROUP_CONCAT(DISTINCT sub2.itemPackingTypeFk ORDER BY sub2.items DESC SEPARATOR ','), ') ') itemPackingTypeFk FROM ( SELECT s.ticketFk, i.itemPackingTypeFk, COUNT(*) items FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN item i ON i.id = s.itemFk WHERE t.routeFk = vRouteFk GROUP BY t.id, i.itemPackingTypeFk )sub2 GROUP BY sub2.ticketFk )sub3 ON sub3.ticketFk = t.id WHERE t.routeFk = vRouteFk ORDER BY priority, Id; END$$ DELIMITER ;