MySQL在insert上加入相同的值

时间:2012-06-05 13:13:41

标签: mysql insert

鉴于这些表格:

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对于每一行都是相同的,子查询的结果类似于{{1} }。我想在一个插入中执行此操作,而不是之后带有更新的插入。我认为它要求select country_id from country where name = 'Canada',但我不确定。

想法?

1 个答案:

答案 0 :(得分:1)

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
);