mysql - 使用外键插入 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),
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 次往返。有没有办法用一个插入来做到这一点?
解决方案
评论中讨论的共识是没有办法用 MySQL 来缩短这个,并且由于评论,原来的 5 语句集被缩短为 2。感谢所有评论的人。
推荐阅读
- ios - 带有触控指示器的 iOS 模拟器屏幕录制
- typescript - 空接口扩展另一个接口是否具有成本效益?TS
- javascript - 如何将 CSS 对象链接到 JavaScript 对象。(在代码中,而不是在文件中。)
- android - android UI中的酷水平工具
- powershell - 在对 WSL 的 Powershell 调用中使用变量
- c# - SignalR GetHubContext 按名称
- json - 如何解析熊猫数据框中的 JSON 列并将新数据框连接到原始数据框?
- azure - Azure B2C 密码字段文本和占位符
- sql - 生成动态列值 SQL
- sql-server - 是否有可能是一个具有共同值但只有一列具有不同数据的表以使其像单行中的枢轴一样?