DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `cache`.`addressFriendship_Update`()
BEGIN

	REPLACE cache.addressFriendship 
		SELECT addressFk1, addressFk2, count(*) friendship
			FROM
				(
				SELECT t.routeFk, t.zoneFk, t.addressFk addressFk1, t2.addressFk addressFk2
					FROM vn.ticket t
						JOIN vn.ticket t2 USING(routeFk, zoneFk)
					WHERE t.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE())
						AND t2.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE())
						AND t.addressFk != t2.addressFk) sub
			GROUP BY addressFk1, addressFk2;
            
	REPLACE cache.zoneAgencyFriendship
		SELECT r.agencyModeFk, t.zoneFk, count(*) friendship
			FROM vn.route r
				JOIN vn.ticket t ON t.routeFk = r.id
			WHERE t.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE())
				AND r.agencyModeFk
				AND t.routeFk
                AND t.zoneFk
			GROUP BY agencyModeFk, zoneFk;
END$$
DELIMITER ;
