使用元组作为外键

时间:2019-06-03 21:48:07

标签: mysql sql foreign-keys

比方说,我有一个名为借用的表格,如下所示:

CREATE TABLE IF NOT EXISTS `borrows` 
( `memberID` int(11) NOT NULL ,
 `ISBN` int(11) NOT NULL ,
 `CopyNr` int(11) NOT NULL ,
  `date_of_borrowing` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `date_of_reminder` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`memberID`,`ISBN`,`CopyNr`,`date_of_borrowing`) )
 ENGINE=InnoDB DEFAULT CHARSET=latin1

我希望此表具有(ISBN,CopyNr)作为另一个名为副本的表的外键。我尝试过的是这样:

ALTER TABLE `borrows` ADD FOREIGN KEY (`ISBN`,`copyNr`) 
REFERENCES `copies`(`copyNr`) ON DELETE RESTRICT ON UPDATE RESTRICT;

这给了我这个错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(`ISBN`),(`copyNr`)) REFERENCES `copies`(`copyNr`) ON DELETE RESTRICT ON UPDATE ' at line 1

我是否应该再创建一个包含(ISBN,CopyNr)元组的列?如果是,这怎么会发生?如果没有,我该如何解决?

更新:这是副本代码:

CREATE TABLE IF NOT EXISTS `copies` 
( `copyNr` int(11) NOT NULL AUTO_INCREMENT,
 `shelf` text NOT NULL,
 `ISBN` int(11) NOT NULL,
 PRIMARY KEY (`copyNr`,`ISBN`) )
 ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1

1 个答案:

答案 0 :(得分:1)

ALTER TABLE `borrows` ADD FOREIGN KEY (`ISBN`,`copyNr`) 
REFERENCES `copies`(`ISBN`,`copyNr`) ON DELETE RESTRICT ON UPDATE RESTRICT;

您应该在表副本上具有复合索引(ISBN,copyNr)