给定这些表:
create table country
(
country_id integer primary key auto_increment,
name varchar(16) unique not null
);
insert into country(name) values
('USA'),
('Canada');
create table network
(
network_id integer primary key auto_increment,
name varchar(32) not null,
country_id integer references country(country_id)
on cascade update
on delete restrict
);
我想执行 insert into network(country_id, name) values
其中 name
是一个值列表,但是 country_id
是每一行都相同,子查询的结果类似于 select country_id from country where name = 'Canada'
。我想在一个插入中完成所有这些,而不是之后插入一个更新。我认为它需要一个 join
但我不确定。
想法?
最佳答案
INSERT INTO network
(country_id, name)
SELECT
c.country_id, n.network_name
FROM
( SELECT country_id
FROM country
WHERE name = 'Canada'
) AS c
CROSS JOIN
( SELECT 'name1' AS network_name UNION ALL
SELECT 'name2' UNION ALL
SELECT 'name3' UNION ALL
...
SELECT 'nameN'
) AS n ;
Sidekick:不要在 MysQL 中内联定义外键,它们会被忽略:
create table network
(
network_id integer primary key auto_increment, --- PK fine, not ignored
name varchar(32) not null,
country_id integer references country(country_id) --- this FK is ignored
on cascade update
on delete restrict
);
在列列表之后分别定义它们。我更喜欢在列之后定义主键约束:
CREATE TABLE network
(
network_id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(32) NOT NULL,
country_id INTEGER NULL,
PRIMARY KEY (network_id),
FOREIGN KEY (country_id) --- FK not ignored
REFERENCES country (country_id)
ON CASCADE UPDATE
ON DELETE RESTRICT
);
关于MySQL 在插入时加入相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10897990/