DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_PriceFix`(vTicketFk INT) BEGIN DELETE sc.* FROM vn.saleComponent sc JOIN vn.sale s ON s.id = sc.saleFk JOIN vn.component c ON c.id = sc.componentFk JOIN vn.componentType ct ON ct.id = c.typeFk WHERE s.ticketFk = vTicketFk AND ct.code = 'other'; UPDATE vn.sale s JOIN ( SELECT sc.saleFk, sum(sc.value ) price FROM vn.saleComponent sc JOIN vn.sale s ON s.id = sc.saleFk WHERE s.ticketFk = vTicketFk GROUP BY sc.saleFk) sub ON sub.saleFk = s.id SET s.price = sub.price; END$$ DELIMITER ;