In my MySQL table I have a simple postal codes table that I have converted it from an .xlsx file.
Country |City |MiniDistrict |Postal Code
---------------------------------------------
Bulgaria |Sofia |Oborishte | 0844
Bulgaria |Sofia |Sredets | 0988
Bulgaria |Plovdiv |Montana | 1299
Bulgaria |Plovdiv |Dyavol | 1288
Bulgaria |Varna |Andeevo | 1574
France |Paris |Mantois |38992
France |Paris |Valois |38764
France |Gard |Lussan |55980
As you can see Country and city names are repeating numerious times. also note that there are same city names in different countries. I want to write a PHP algorithm where I’ll generate a country table, a city table, and a minidistrict-postalcode table into MySQL. The country table is easy, SELECT DISTINCT. What algorythm should I write for the other tables? The algorytm idea will be enough for me, no need for the coding part.
The “algorithm” is this: you notice that every MiniDistrict has a PostalCode, and every PostalCode has its MiniDistrict. So you put these together in a single table, and associate each pair with an unique ID.
Then you notice that each city is a single object, and the same for the countries, so you create two tables for them, each with its own ID.
Now you must store a relationship between minidistricts and cities. But this is a many-to-one relationship: many minidistricts may belong to the same city, but the same minidistrict can’t belong to two cities.
So you add a reference to
cities.idas foreign keycity_idto minidistricts.The relationship structure is the same between cities and countries. So again you add a foreign key, this time
country_idtocountries.idintocities.At that point, you can also create a
VIEWto see your data as before:You can also populate your new
districts,citiesandcountriesfrom your existing data, beginning with the table that has no foreign keys:(This will insert twice a city if it exists with the same name in two countries – one with each country ID – but that’s as it should be: city names are normally not unique).