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.

有帮助吗?

解决方案

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.

其他提示

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;
许可以下: CC-BY-SA归因
不隶属于 dba.stackexchange
scroll top