ALTER TABLE vn.supplier CHANGE companySize companySize enum('small','medium','big') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL NULL AFTER stamp, ADD geoFk int(11) DEFAULT NULL NULL AFTER companySize, ADD CONSTRAINT supplier_zoneGeo_FK FOREIGN KEY (geoFk) REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE; CREATE OR REPLACE TEMPORARY TABLE tmp.tSupplierGeo (PRIMARY KEY (id)) ENGINE = MEMORY SELECT s.id, p.geoFk FROM supplier s JOIN town t ON t.provinceFk = s.provinceFk JOIN postCode p ON p.townFk = t.id LEFT JOIN supplierAddress sad ON sad.supplierFk = s.id GROUP BY s.id ORDER BY (s.city SOUNDS LIKE t.`name`) DESC, (p.code = s.postCode) DESC, (p.code = sad.postalCode) DESC; UPDATE supplier s JOIN tmp.tSupplierGeo tsg ON tsg.id = s.id SET s.geoFk = tsg.geoFk; DROP TEMPORARY TABLE tmp.tSupplierGeo;