MySQL 在插入时加入相同的值

标签 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 是每一行都相同,子查询的结果类似于 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/

相关文章:

c# - ConnectionString 未正确读取 - EF Core

mysql - NOT LIKE 对 mysql 查询

mysql - 在我的服务器上说 "Could not load file or assembly ' MySql.Web ...“但我的应用程序中有 mysql

php - 使用 PHP 从数据库获取图像

mysql - 如何将来自三个 Perl 数组的数据插入到单个 MySQL 表中?

php - 将数据插入 WordPress 插件中的新表

mysql - NOT IN WHERE 子句错误

php - 创建一个动态的 php insert into mysql 函数?

sql - Mysql慢速插入

mysql - INSERT INTO 与 SELECT 和外部值