我正在使用MySQL和NodeJS,我有一个看起来像这样的表:
CREATE TABLE IF NOT EXISTS `keycomponent`.`Transaction` (
`TransactionID` INT NOT NULL,
`TransactionDate` DATE NOT NULL,
`Amount` MEDIUMTEXT NOT NULL,
`CreationDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`TransactionDescriptionPK` INT NOT NULL,
`FilePK` VARCHAR(255) NOT NULL,
PRIMARY KEY (`TransactionID`),
UNIQUE INDEX `TransactionID_UNIQUE` (`TransactionID` ASC),
INDEX `FilePK_idx` (`FilePK` ASC),
INDEX `TransactionDescriptionPK_idx` (`TransactionDescriptionPK` ASC),
CONSTRAINT `TransactionDescriptionPK`
FOREIGN KEY (`TransactionDescriptionPK`)
REFERENCES `keycomponent`.`TransactionDescription` (`TransactionDescriptionPK`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `FilePK`
FOREIGN KEY (`FilePK`)
REFERENCES `keycomponent`.`File` (`Filename`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
它包含两个外键,当我尝试将值插入另一个表时,我收到此错误
Error: ER_NO_DEFAULT_FOR_FIELD: Field 'TransactionDescriptionPK' doesn't have a default value
列不应该自动从另一个表中获取主键吗?
我的查询'
'INSERT INTO Transaction '+
'SET TransactionID = ?, TransactionDate = ?, Amount = ?, TransactionDescriptionPK = ?, FilePK = ?',
[transId,date,amount,"primary key to the TransactionDescription table","primary key to the File table"]
答案 0 :(得分:0)
不,外键不会自动从另一个表中获取值。应该如何确定mysql应该从父表中获取哪个TransactionDescriptionPK值?您必须为声明为非null且没有默认值的所有外键字段提供值,就像对任何其他类似字段一样。
旁注:如果某个字段被声明为pk,则不必在其上创建唯一索引。
答案 1 :(得分:0)
我不相信你的错误与外键有任何关系。您的TransactionDescriptionPK
表中有一列TransactionDescription
,该列已设置为not null
,但您在此插入语句中未提供任何值。