问题
I have a database in which there is Country, city , states , postcodes in one table with huge set of records. I want to normalize the database structure to avoid redundancy and remove any data duplication. Should I split database and make separate tables for Country, City, state and postcode?
Or merge country , city , state, postcode in Address table?
回答1:
The following tables could be used for addresses in North America. Counties (which would also contain Parishes and other similar geographical subdivisions) is US-centric.
In the addresses
table I allow the city_id
and county_id
to be NULL
because, based on HLGEM's comment, you can be in a city OR a county but not both in the state of Virginia. The application code would need to enforce the rule that at least one of these fields is not NULL
.
addresses
id unsigned int(P)
street varchar(50)
extended varchar(50) // Default NULL
city_id unsigned int(F cities.id) Default NULL
county_id unsigned int(F counties.id) Default NULL
zip varchar(6) // Will handle all north American zips
zip4 char(4) // Default NULL
lat decimal(10,8) // Allows for ~1mm accuracy at equator. Default NULL
lon decimal(11,8) // Allows for ~1mm accuracy at equator. Default NULL
cities
id unsigned int(P)
state_id unsigned int(F states.id)
name varchar(45)
fips unsigned int // Default NULL
census_code unsigned int // Default NULL
census_class_code char(2) // Default NULL
gsa_code unsigned int // Default NULL
opm_code unsigned int // Default NULL
city_id
and county_id
form the Primary key and are foreign keys to their respective tables.
cities_counties
city_id unsigned int(F cities.id) ---\_(P)
county_id unsigned int(F counties.id)--/
counties
id unsigned int(P)
state_id unsigned int(F states.id)
name varchar(50)
fips unsigned int // Default NULL
See http://en.wikipedia.org/wiki/ISO_3166-1
countries
id char(2)(P)
iso3 char(3)(U)
iso_num char(3)(U)
name varchar(44)(U)
See FIPS state codes, FIPS region codes and ISO 3166-2.
states
id unsigned int(P)
country_id char(2)(F countries.id)
code varchar(3)(I)
name varchar(45)
fips unsigned int // Default NULL
来源:https://stackoverflow.com/questions/21015175/country-city-state-post-code-table-design