mysql - insert multiple values sharing same foreign key
-
01-03-2021 - |
Question
I have the following tables:
create table countries (
country_id tinyint unsigned,
iso_alpha3_code varchar(4)
);
create table provinces (
province_id bigint unsigned,
province_name varchar(50),
country_id tinyint unsigned,
foreign key (country_id) references countries(country_id) on delete restrict on update cascade
);
For inserting records into provinces, the corresponding country_id
is needed:
insert into provinces (province_name, country_id) VALUES
('Alabama', (select country_id from countries where iso_alpha3_code = 'USA')),
('California', (select country_id from countries where iso_alpha3_code = 'USA')),
('Alaska', (select country_id from countries where iso_alpha3_code = 'USA'));
How to insert these records without repeated-select statements to get the foreign key? Can something like CTE be used?
PS: I found this, but it's for postgreSQL.
La solution
Here's another approach:
SELECT @usa := country_id from countries where iso_alpha3_code = 'USA';
insert into provinces (province_name, country_id)
VALUES
('Alabama', @usa),
('California', @usa),
('Alaska', @usa);
But I contend that you should not normalize country_code
; simply use the standard 3-letter (or 2-letter) codes.
The savings of 2 (or 1) byte is insignificant. The cost of the JOIN
, though small, is non-zero.
If you need the table countries
for other reasons (population, fullname, etc), then let the 3- or 2-character code be the "natural" PRIMARY KEY
for that table.
Autres conseils
insert into provinces (province_name, country_id)
SELECT t1.province_name, t2.country_id
FROM ( SELECT 'Alabama' province_name UNION SELECT 'California' UNION SELECT 'Alaska') t1
JOIN (select country_id from countries where iso_alpha3_code = 'USA') t2;
Licencié sous: CC-BY-SA avec attribution
Non affilié à dba.stackexchange