I am dealing with phone system and have to work with multiple service vendors. For one vendor I have a MySQL table country_codes like this -
--
If you need to do the fix the data ONLY once, you can try this approach:
0) Backup your data, or better, run the query on copy of the data.
1) Creates a table that contains non-zero country codes. We need separate table because it says in MySQL manual that:
Currently, you cannot update a table and select from the same table in a subquery.
CREATE TABLE country_codes_list (
country_code INT NOT NULL PRIMARY KEY
);
INSERT INTO country_codes_list
SELECT country_code
FROM country_codes
WHERE country_code <> 0;
2) Update all rows where country code is 0 by finding the country code that matches the beginning of the area code:
UPDATE country_codes AS country_codes_zero SET country_code = (
SELECT country_code
FROM country_codes_list
WHERE country_codes_list.country_code = SUBSTRING(country_codes_zero.area_code, 1, LENGTH(country_codes_list.country_code))
) WHERE country_code = 0;
This could be a very slow query because it uses a co-related sub-query. But it should fix the data in one go.