DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`supplier_getGeo`(vSelf INT) RETURNS int(11) DETERMINISTIC BEGIN /** * Returns the geo for the passed supplier. * * @param vSelf The address id * @return The geo id */ DECLARE vGeoFk INT; SELECT p.geoFk INTO vGeoFk FROM supplier s JOIN town t ON t.provinceFk = s.provinceFk JOIN postCode p ON p.townFk = t.id AND (p.code = s.postCode OR s.postCode IS NULL) LEFT JOIN supplierAddress sad ON sad.supplierFk = s.id JOIN zoneGeo zg ON zg.id = p.geoFk WHERE s.id = vSelf ORDER BY (s.city SOUNDS LIKE t.name) DESC, (p.code = s.postCode) DESC, (p.code = sad.postalCode) DESC LIMIT 1; RETURN vGeoFk; END$$ DELIMITER ;