DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`zone_getOptionsForLanding`(vLanded DATE, vShowExpiredZones BOOLEAN) BEGIN /** * Gets computed options for the passed zones and delivery date. * * @table tmp.zone(id) The zones ids * @param vLanded The delivery date * @return tmp.zoneOption The computed options */ DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; CREATE TEMPORARY TABLE tmp.zoneOption ENGINE = MEMORY SELECT zoneFk, `hour`, travelingDays, price, bonus, vLanded landed, TIMESTAMPADD(DAY, -travelingDays, vLanded) shipped FROM ( SELECT t.id zoneFk, TIME(IFNULL(e.`hour`, z.`hour`)) `hour`, IFNULL(e.travelingDays, z.travelingDays) travelingDays, IFNULL(e.price, z.price) price, IFNULL(e.bonus, z.bonus) bonus FROM tmp.zone t JOIN zone z ON z.id = t.id JOIN zoneEvent e ON e.zoneFk = t.id WHERE ( e.`type` = 'day' AND e.dated = vLanded ) OR ( e.`type` != 'day' AND e.weekDays & (1 << WEEKDAY(vLanded)) AND (e.`started` IS NULL OR vLanded >= e.`started`) AND (e.`ended` IS NULL OR vLanded <= e.`ended`) ) ORDER BY zoneFk, CASE WHEN e.`type` = 'day' THEN 1 WHEN e.`type` = 'range' THEN 2 ELSE 3 END LIMIT 10000000000000000000 ) t GROUP BY zoneFk; DELETE t FROM tmp.zoneOption t JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id WHERE eg.zoneExclusionFk IS NULL; IF NOT vShowExpiredZones THEN DELETE FROM tmp.zoneOption WHERE shipped < util.VN_CURDATE() OR (shipped = util.VN_CURDATE() AND util.VN_CURTIME() > `hour`); END IF; END$$ DELIMITER ;