1

鉴于这些表:

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) valueswherename是一个值列表,但country_id对于每一行都是相同的,子查询的结果类似于select country_id from country where name = 'Canada'. 我想在一次插入中完成这一切,而不是在插入之后进行更新。我认为它需要一个join,但我不确定。

想法?

4

1 回答 1

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
);
于 2012-06-05T13:21:51.953 回答