假设我有3或4个表,其中一些表与父表连接。我想同时向这些表提交数据。
Table: table1
--------------------------------------------------------------------
| table1Id(AI)(PK) | blah1 | blah2 | blah3 | blah3 | blah4 | [....]
--------------------------------------------------------------------
Table: table2
--------------------------------------------------------------------
| table2Id(AI)(PK) | clah1 | clah2 | clah3 | clah4 | [....] | table1Id (FK)
--------------------------------------------------------------------
Table: table3
--------------------------------------------------------------------
| table3Id(AI)(PK) | flah1 | flah2 | flah3 | flah4 | [....] | table1Id (FK)
--------------------------------------------------------------------
我的数据库SQL代码是
CREATE TABLE IF NOT EXISTS `mydb`.`table1` (
`table1Id` INT NULL AUTO_INCREMENT,
`blah1` VARCHAR(45) NULL,
`blah2` VARCHAR(45) NULL,
`blah3` VARCHAR(45) NULL,
`blah4` VARCHAR(45) NULL,
PRIMARY KEY (`table1Id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `mydb`.`table2` (
`table2Id` INT NULL AUTO_INCREMENT,
`clah1` VARCHAR(45) NULL,
`clah2` VARCHAR(45) NULL,
`clah3` VARCHAR(45) NULL,
`clah4` VARCHAR(45) NULL,
`table1Id` INT NULL,
PRIMARY KEY (`table2Id`),
INDEX `FK_table1_table2_idx` (`table1Id` ASC),
CONSTRAINT `FK_table2_table1`
FOREIGN KEY (`table1Id`)
REFERENCES `mydb`.`table1` (`table1Id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `mydb`.`table3` (
`table3Id` INT NULL AUTO_INCREMENT,
`flah1` VARCHAR(45) NULL,
`flah2` VARCHAR(45) NULL,
`flah3` VARCHAR(45) NULL,
`flah4` VARCHAR(45) NULL,
`table1Id` INT NULL,
PRIMARY KEY (`table3Id`),
INDEX `FK_table3_table1_idx` (`table1Id` ASC),
CONSTRAINT `FK_table3_table1`
FOREIGN KEY (`table1Id`)
REFERENCES `mydb`.`table1` (`table1Id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
INSERT INTO table1 (blah1, blah2, blah3, blah4, blah5)
VALUES (NULL, NULL, NULL, NULL, NULL);
INSERT INTO table2 (clah1, clah2, clah3, clah4, clah5, table1Id)
VALUES (NULL, NULL, NULL, NULL, NULL, LAST_INSERT_ID());
INSERT INTO table3 (flah1, flah2, flah3, flah4, flah5, table1Id)
VALUES (NULL, NULL, NULL, NULL, NULL, LAST_INSERT_ID());
以上代码正常工作,但如果我在table1表上应用自定义auto_increment,则Insert查询显示错误:
1452 - 无法添加或更新子行:外键约束 失败
ALTER TABLE table1 AUTO_INCREMENT=300;
我该如何解决这个问题?我想将所有数据提交到table1 - table3 Table。
我还尝试了事务提交,这也没有工作。
答案 0 :(得分:1)
在第三个查询中,LAST_INSERT_ID()
将提供table2Id
而不是table1Id
的值。但是,虽然未修改自动增量,但table1和table2都从1开始。因此外键验证成功。
例如在新桌子上:
您可以做的是,在第一个查询之后将LAST_INSERT_ID()保留在变量中,并在其余查询中使用它。
插入的完整代码是:
INSERT INTO table1 (blah1, blah2, blah3, blah4)
VALUES (NULL, NULL, NULL, NULL);
SET @LID = LAST_INSERT_ID();
INSERT INTO table2 (clah1, clah2, clah3, clah4, table1Id)
VALUES (NULL, NULL, NULL, NULL, @LID);
INSERT INTO table3 (flah1, flah2, flah3, flah4, table1Id)
VALUES (NULL, NULL, NULL, NULL, @LID);
P.S。:我已经修改了插入查询,因为它们包含一些无效的列。