首页 > 解决方案 > 使用外键插入 MySQL 并在不存在时自动创建新的外键

问题描述

我有两个具有外键关系的表。我们称它们为argsarglist

create table args (id int not null,
  arg varchar not null,
  primary key (id),
  unique index (arg)
);

create table arglist (id int not null,
   arg1 int not null,
   arg2 int not null,
   foreign key arg1 references args(id),
   foreign key arg2 references args(id),
   primary key (id),
   index (arg1),
   index (arg2)
);

将任意 args 插入 arglist 的不太优雅的方法是先执行 an insert ignore,然后执行 aselect以获取每个 arg 的 id,然后将其插入 arglist。

有点像:

INSERT IGNORE INTO args (arg) VALUES ('newarg1'),('newarg2');
INSERT INTO arglist (arg1,arg2) VALUES ((SELECT id from args where arg='newarg1'),(SELECT id from args where arg='newarg2'));

这是到数据库服务器的 2 次往返。有没有办法用一个插入来做到这一点?

标签: mysqlforeign-keys

解决方案


评论中讨论的共识是没有办法用 MySQL 来缩短这个,并且由于评论,原来的 5 语句集被缩短为 2。感谢所有评论的人。


推荐阅读