假设我有3或4个表,其中一些表与父表连接。我想同时向这些表提交数据。
public void SetText(params int[] xs) { }
public class Impinj
{
public class OctaneSdk
{
public class TagData { }
public class ImpinjTimestamp { }
}
}
public class ImpinjReader { }
public class TagReport : List<Tag> { }
public class Tag
{
public ushort AntennaPortNumber;
public Impinj.OctaneSdk.TagData Epc;
public Impinj.OctaneSdk.ImpinjTimestamp LastSeenTime;
}
我的数据库SQL代码是
Table: table1
--------------------------------------------------------------------
| table1Id(AI)(PK) | blah1 | blah2 | blah3 | blah3 | [....]
--------------------------------------------------------------------
Table: table2
--------------------------------------------------------------------
| table2Id(AI)(PK) | clah1 | clah2 | clah3 | clah4 | [....] | table1Id (FK)
--------------------------------------------------------------------
Table: table3
--------------------------------------------------------------------
| table3Id(AI)(PK) | flah1 | flah2 | flah3 | flah4 | [....] | table1Id (FK)
--------------------------------------------------------------------
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;
此查询显示错误:
1452 - 无法添加或更新子行:外键约束 失败
但是如果只插入2个表就可以了
INSERT INTO table1 (table1Id, 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());
答案 0 :(得分:0)
尝试
INSERT INTO table1 (table1Id, blah1, blah2, blah3, blah4, blah5)
VALUES (101, NULL, NULL, NULL, NULL, NULL);
INSERT INTO table2 (clah1, clah2, clah3, clah4, clah5, table1Id)
VALUES (NULL, NULL, NULL, NULL, NULL, 101);
INSERT INTO table3 (flah1, flah2, flah3, flah4, flah5, table1Id)
VALUES (NULL, NULL, NULL, NULL, NULL, 101);