简体   繁体   中英

MySQL insert country iso or country id from another table

I want to insert each visitor's country in my database. Maxmind returns the 2 letters country ISO that I could store in a VARCHAR(2) , that would use 2 bytes, or, alternatively, I can use an UNSIGNED TINYINT that would use 1 byte, and would be the id from a table with all the countries.

However I hit a bump; I need MyISAM engine for fast insertions, but MyISAM does not support FOREIGN KEYS , so I guess that for each insertion, I will have to make a select in the countries table to retrieve the country id.

I don't know what is the best option, I absolutely need to use MyISAM as there will be lots of insertions but I don't want to constantly make SELECTs to retrieve the country id.

If you only need the 2-letter ISO country code (and not the country name, language, or other information) then I'd say that storing it as CHAR(2) with no external table would be less resource-intensive than storing it as SMALLINT (TINYINT wouldn't be enough to cover all countries) with a lookup to an additional table.

Note: there is no need for VARCHAR(2) in this case, CHAR(2) would be more efficient.

You can create a associtive array from the country table. Make the country id as the key for this array. Then make it available to your views. So from with in views you can do a lookup against the country array and display the relevent country. for example

<?php echo $country[$customer['country_id']]['country_name']; ?>

The only difference between having FK support and not having it is ensuring integrity. If you were to use an engine that supported FK's it wouldnt allow you to set the country without having that record's ID.

That said the number of countries is semi-static and we are only talking in the hundreds... you could potentially keep keep all these in memory and have the ID's avialable.

Alternatively you could do a select during the insert like:

INSERT INTO sometable (col1,col2,country_id) VALUES('val1','val2', (SELECT id FROM countries WHERE iso_code = ?))

? would be your ISO value.

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