每当我尝试在表格中插入外键时,我都会收到该消息:
错误代码:1215。无法添加外键约束0.281秒
我的创建表格代码:
CREATE TABLE `test`.`buy`(
`id` INT NOT NULL AUTO_INCREMENT,
`id_customer` INT UNSIGNED NOT NULL,
`code` VARCHAR(45) NOT NULL,
PRIMARY KEY(`id`),
UNIQUE INDEX `code_UNIQUE`(`code`),
CONSTRAINT `id_customer` FOREIGN KEY(`id_customer`) REFERENCES `test`.`customer`(`id_customer`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `code` FOREIGN KEY(`code`) REFERENCES `test`.`product`(`code`) ON DELETE RESTRICT ON UPDATE CASCADE
)
我该怎么办?
答案 0 :(得分:0)
请在下次格式化您的代码,以便更容易阅读。
您不需要CONSTRAINT xxx
位,请尝试此操作:
CREATE TABLE test.buy (
id INT NOT NULL AUTO_INCREMENT,
id_customer INT UNSIGNED NOT NULL,
code VARCHAR(45) NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX code_UNIQUE (code),
FOREIGN KEY (id_customer)
REFERENCES test.customer (id_customer)
ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (code)
REFERENCES test.product (code)
ON DELETE RESTRICT ON UPDATE CASCADE
);
如果仍然不起作用,请确保您引用的其他表(test.customer和test.product)已存在,并且它们具有相同数据类型的匹配字段。