DROP TRIGGER IF EXISTS `vn2008`.`expeditionsBeforeUpdate`;

DELIMITER $$
USE `vn2008`$$
CREATE DEFINER=`root`@`%` TRIGGER `vn2008`.`expeditionsBeforeUpdate`
BEFORE UPDATE ON `vn2008`.`expeditions`
FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
	IF NEW.counter <> OLD.counter THEN
		IF (SELECT COUNT(*) FROM expeditions e 
				INNER JOIN Tickets t1 ON e.ticket_id = t1.Id_Ticket
				INNER JOIN Tickets t2 ON t2.Id_Consigna = t1.Id_Consigna AND DATE(t2.Fecha) = DATE(t1.Fecha) 
			WHERE t1.Id_Ticket = NEW.ticket_id AND counter = NEW.counter) > 0 THEN
			SET NEW.expeditions_id = NULL;
		END IF;
	END IF;
END$$
DELIMITER ;
