在一个操作中填充 MySQL 记录一对多相关表
我有两个 MySQL 表,它们之间具有一对多关系。例如:
CREATE TABLE test1 (
pk1 INTEGER AUTO_INCREMENT PRIMARY KEY,
testvalue1 INTEGER
);
CREATE TABLE test2 (
pk2 INTEGER AUTO_INCREMENT PRIMARY KEY,
testvalue2 VARCHAR(50),
fk2 INTEGER NOT NULL,
FOREIGN KEY (fk2) REFERENCES test1 (pk1)
);
如果我想在两个表中插入记录,我可以先在 PK 表中插入一条记录(例如 INSERT INTO test1 SET testvalue1=100
),确定 PK 值(例如 SELECT MAX(pk1) AS LastId FROM test1
或使用 LAST_INSERT_ID()
) 最后使用该值填充第二个表中的 FK 列。
但是是否有可能在 1 个命令/查询/操作中实现这一切?那么让 MySQL 使用自动增量来填充 PK 和 FK 值吗?
I have two MySQL tables with an one-to-many relationship between them. For example:
CREATE TABLE test1 (
pk1 INTEGER AUTO_INCREMENT PRIMARY KEY,
testvalue1 INTEGER
);
CREATE TABLE test2 (
pk2 INTEGER AUTO_INCREMENT PRIMARY KEY,
testvalue2 VARCHAR(50),
fk2 INTEGER NOT NULL,
FOREIGN KEY (fk2) REFERENCES test1 (pk1)
);
If I want to insert records in both tables I can first insert a record in the PK table (e.g. INSERT INTO test1 SET testvalue1=100
), determine the PK value (e.g. SELECT MAX(pk1) AS LastId FROM test1
or use LAST_INSERT_ID()
)
and finally use that value to fill the FK column in the second table.
But is it possible to achieve this all in 1 command/query/action? So let's MySQL fill in the PK- and FK-values using the AUTO INCREMENTs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用两个 INSERT 命令;或者尝试使用 INSERT 触发器。
编辑:
--带有触发器的示例:
You should use two INSERT commands; or try to use an INSERT-trigger.
EDIT:
--An example with trigger: