For a given table called PostTable
Here is the Country Table
CREATE TABLE Country
(
id int not null,
name varchar(32) not null,
unique key (name),
primary key (id)
);
OK, what about State / Province?
CREATE TABLE State
(
id int not null,
country_id int not null,
name varchar(32) not null,
primary key (id),
unique key (name)
);
How about Counties?
CREATE TABLE County
(
id int not null,
country_id int not null,
state_id int not null,
name varchar(32) not null,
unique key (name,state_id),
primary key (id)
);
Why would the County have to have (name,state_id) as a unique key combo? For example, there are 10 countries in the USA named Orange County (One is in New York, another is in California)
Let's go with City
CREATE TABLE City
(
id int not null,
county_id int not null,
state_id int not null,
name varchar(32) not null,
unique key (name,state_id),
unique key (name,country_id),
primary key (id)
);
Why would the City have to have (name,country_id) as a unique key combo? For example, there is City named Rome in all Continents.
Why would the City have to have (name,state_id) as a unique key combo? For example, there is Jersey City, NJ and Jersey City, WI. There is also Hollywood, CA and Hollywood, FL.
Based on this, you could do your JOINs from these perspectives
- Country -> State
- State -> County
- County -> City
- State -> City
Just remember that the UNIQUE KEY declarations allow combinations of
- identical County Name in multiple States
- identical City Name in multiple States
- identical City Name in multiple Countries
I am not in the mood for figuring out strange oddities like
- Minneapolis-StPaul, Minnesota
- Kansas City, MO and Kansas City, KS
- Any City that sits in two different Counties
To shorten JOINs, you could just keep country_id, county_id, state_id, city_id with each PostTable row. Otherwise, you could be chaining all these tables deeper and deeper. This would definitely require proper tuning of sort_buffer_size and join_buffer_size.