我似乎无法在两张桌子之间设置Foreign Key
。
以下是每个表的CREATE
子句:
CREATE TABLE IF NOT EXISTS `dbname`.`CallRecord` (
`id` INT NOT NULL AUTO_INCREMENT,
`user_id` INT NOT NULL,
`city_id` INT NOT NULL,
`created` DATETIME NULL,
`timestamp` TIMESTAMP NULL,
PRIMARY KEY (`id`),
INDEX `user_id_fk_idx` (`user_id` ASC),
INDEX `city_id_fk_idx` (`city_id` ASC),
CONSTRAINT `user_id_fk`
FOREIGN KEY (`user_id`)
REFERENCES `dbname`.`User` (`id`)
ON DELETE RESTRICT
ON UPDATE NO ACTION,
CONSTRAINT `city_id_fk`
FOREIGN KEY (`city_id`)
REFERENCES `dbname`.`City` (`id`)
ON DELETE RESTRICT
ON UPDATE NO ACTION)
ENGINE = InnoDB;
这是另一张桌子:
CREATE TABLE IF NOT EXISTS `dbname`.`DataCallAssoc` (
`id` INT NOT NULL AUTO_INCREMENT,
`data_id` INT NOT NULL,
`call_record_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `data_id_fk_idx` (`data_id` ASC),
INDEX `call_record_id_fk_idx` (`call_record_id` ASC),
CONSTRAINT `data_id_fk`
FOREIGN KEY (`data_id`)
REFERENCES `dbname`.`Data` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `call_record_id_fk`
FOREIGN KEY (`call_record_id`)
REFERENCES `dbname`.`CallRecord` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
问题在于CONSTRAINT
的最后DataCallAssoc
:
CONSTRAINT `call_record_id_fk`
FOREIGN KEY (`call_record_id`)
REFERENCES `dbname`.`CallRecord` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
我收到此错误:
Error creating foreign key on call_record_id (check data types)
即使我单独创建表和外键。每个其他外键都可以工作,甚至其他指向CallRecord.id
作为外键的表也可以工作。
我还检查了CallRecord.id
在结构方面与DataCallAssoc.call_record_id
相同。
答案 0 :(得分:34)
如果在另一个表中已经有一个同名的外键,则会出现创建外键错误...(检查数据类型)错误。因此,如果您遇到这个最无用的错误消息,请确保您的数据类型匹配,并且外键名称是唯一的。希望这有助于某人。
答案 1 :(得分:7)
除了确保数据类型相同外,对于某些类型(如bigint(20)),如果主键是无符号的,则外键也必须是无符号的。 "无符号"是一个领域的属性之一。
答案 2 :(得分:1)
我能够在localhost中重新创建表,我从第一个create
删除了这个表,因为你没有显示USER
或City
表的结构,所以错误应该在那里
CONSTRAINT `user_id_fk`
FOREIGN KEY (`user_id`)
REFERENCES `dbname`.`User` (`id`)
ON DELETE RESTRICT
ON UPDATE NO ACTION,
CONSTRAINT `city_id_fk`
FOREIGN KEY (`city_id`)
REFERENCES `dbname`.`City` (`id`)
ON DELETE RESTRICT
ON UPDATE NO ACTION)
这就是我使用的原因。
CREATE TABLE IF NOT EXISTS `CallRecord` (
`id` INT NOT NULL AUTO_INCREMENT,
`user_id` INT NOT NULL,
`city_id` INT NOT NULL,
`created` DATETIME NULL,
`timestamp` TIMESTAMP NULL,
PRIMARY KEY (`id`),
INDEX `user_id_fk_idx` (`user_id` ASC),
INDEX `city_id_fk_idx` (`city_id` ASC)
)
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `DataCallAssoc` (
`id` INT NOT NULL AUTO_INCREMENT,
`data_id` INT NOT NULL,
`call_record_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `data_id_fk_idx` (`data_id` ASC),
INDEX `call_record_id_fk_idx` (`call_record_id` ASC),
CONSTRAINT `call_record_id_fk`
FOREIGN KEY (`call_record_id`)
REFERENCES `CallRecord` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB