I have a table called countries that has the structure: ID, LOCALES_ID, NAME
I want to handle multiple locales with this table, so I need that for different LOCALES_ID, the ID is the same. So, if I insert:
INSERT INTO countries (locales_id, name)
VALUES
('1', 'Lorem'),
('2', 'Ipsum');
The final result I want on the database is:
ID | LOCALES_ID | NAME
1 | 1 | Lorem
1 | 2 | Ipsum
But with the INSERT I tried I got the next result:
ID | LOCALES_ID | NAME
1 | 1 | Real insert
2 | 2 | Real insert #2
My countries table has a PRIMAY index on the columns ID and LOCALES_ID and I supposed that this was all what I need for when I insert different locales I get the same ID.
How I can solve this problem?
Thank you in advance,
What you’re trying to implement here is a one-to-many relationship, i.e. each Country can have multiple Locales. This cannot be achieved with a single table, as you would find yourself with the same Country appearing multiple times. What you should do is split the data in two tables. You can find an example below.
Structure for Countries table
– ID int, autoincrement, primary key
– Name varchar
Structure for Locales table
– CountryID int, primary key
– LocaleID int, primary key
– Name varchar
Handling INSERT
– To insert in Countries table, simply populate Name field (or any other fields you may need):
The ID field will be populated automatically. For this example, we can imagine that “Ireland” will have ID = 1.
– To insert in Locales, you’ll pass three values, i.e. CountryID, LocaleID and Name.
This query will insert LocaleID for the Country with ID = 1 (i.e. Ireland) and ‘Lorem’ as a name. To insert ‘Ipsum’, you’ll do the same:
Where LocaleID will be 2, for Country with ID = 1 and name will be ‘Ipsum’.
How to retrieve the data
Since now data is split in two tables, you’ll have to use a Join to put it together. It’s very simple:
That’s it. Now your query will return the Country with its name in the proper Locale, if it exists. If it doesn’t, CountryName and LocaleID will be NULL.
Update 2012/08/11 – How to use a single table (not recommended)
If you wish to use a single table for the Countries, you’ll have to handle the Country IDs manually. That is, you’ll perform an INSERT as follows:
This, however, will leave you with an issue. Imagine the table contains an unspecified number of Countries and you have to add a new one. What ID would you give to this new Country?