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 vn.supplier s JOIN vn.town t ON t.provinceFk = s.provinceFk JOIN vn.postCode p ON p.townFk = t.id AND (p.code = s.postCode OR s.postCode IS NULL) LEFT JOIN vn.supplierAddress sad ON sad.supplierFk = s.id JOIN vn.zoneGeo zg ON zg.id = p.geoFk GROUP BY s.id ORDER BY (s.city SOUNDS LIKE t.`name`) DESC, (p.code = s.postCode) DESC, (p.code = sad.postalCode) DESC; UPDATE vn.supplier s JOIN tmp.tSupplierGeo tsg ON tsg.id = s.id SET s.geoFk = tsg.geoFk; DROP TEMPORARY TABLE tmp.tSupplierGeo;