简体   繁体   中英

Best way to store and retrieve location field

I am using PHP and MySQL (with Laravel framework). I need to have a field Location. I have two questions:

  1. How do I retrieve the list of Cities and Countries in an optimized way?
  2. How do I store them in the database for an entity in an optimized way?

I have seen open implementations like the below:

If I use any Self Hosted service, I have to store the whole set of data to the the database. This would be huge since the list is around 15 - 20 MB for just CSV and if I store it in MySQL, it will go more than that and it might be a performance issue.

On the other hand, if I use any Hosted REST API service, this would be tedious job to convert it to our native format and there are issues of migration, like:

  1. We can't add new cities.
  2. Tedious job if the service is down.

And for the second issue, what would be the best way to store the location in the database? Would it be good to store it in plain text? If that's the case, there will be like 100s of records with data like:

New York, United States
New York, United States
New York, United States
New York, United States
New York, United States
New York, United States
London, United Kingdom
London, United Kingdom
London, United Kingdom

How do I tackle these issues? What is the best practise? Thanks in advance.

Personally, I would load the information into a SQL database, because of the reasons you provide, preventing problems when the 3rd party service is down or changes.

I would take the CSV file, normalise it, and import it into the database.

Country (id, name);
Region (id, name, country_id);
City (id, name, region_id);

This way you are able to select the country for the city.

SELECT co.name 
FROM City c 

LEFT JOIN Region r 
ON c.region_id = r.id 

LEFT JOIN Country co
ON r.country_id = co.id

WHERE city.name = '$city';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM