user2593609
user2593609

Reputation: 43

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.

Upvotes: 4

Views: 932

Answers (3)

prodigitalson
prodigitalson

Reputation: 60413

The only difference between having FK support and not having it is ensuring integrity. If you were to use an engine that supported FKs, it wouldn't 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 IDs available.

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.

Upvotes: 0

gbe
gbe

Reputation: 163

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.

Upvotes: 1

DevZer0
DevZer0

Reputation: 13535

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']; ?>

Upvotes: 0

Related Questions