ALTER TABLE vn.address ADD geoFk int(11) DEFAULT NULL NULL AFTER isLogifloraAllowed, ADD CONSTRAINT address_zoneGeo_FK FOREIGN KEY (geoFk) REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE; CREATE OR REPLACE TEMPORARY TABLE tAddressGeo (PRIMARY KEY (id)) ENGINE = MEMORY SELECT a.id, p.geoFk FROM address a JOIN town t ON t.provinceFk = a.provinceFk JOIN postCode p ON p.townFk = t.id GROUP BY a.id ORDER BY (a.city SOUNDS LIKE t.`name`) DESC, (p.code = a.postalCode) DESC; UPDATE address a JOIN tAddressGeo tag ON tag.id = a.id SET a.geoFk = tag.geoFk; DROP TEMPORARY TABLE tAddressGeo;