使用外键插入MySQL并自动创建新的外键(如果不存在)

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

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),index (arg1),index (arg2)
);

将任意args插入arglist的一种不太好的方法是执行insert ignore,然后执行select以获取每个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次往返。是否可以通过单个插入来完成此操作?

biefanwoxingme 回答:使用外键插入MySQL并自动创建新的外键(如果不存在)

在评论中进行讨论的共识是,使用MySQL无法将其缩短,因此,由于评论,原始的5语句集缩短为2。感谢所有发表评论的人。 / p>

本文链接:https://www.f2er.com/3116751.html

大家都在问