我目前正在为一家公司的预订系统编码,他们也想要一个任务管理系统,但是我遇到了一个错误,这使我发疯。
Executing SQL script in server
ERROR: Error 1215: Cannot add foreign key constraint
SQL Code:
-- -----------------------------------------------------
-- Table `bvsv_system`.`task`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `bvsv_system`.`task` (
`idtask` INT(11) NOT NULL,
`attGora` VARCHAR(200) NULL,
`status` VARCHAR(45) NULL,
`to` VARCHAR(45) NULL,
`jobstatus_id` INT(11) NOT NULL,
`worker_personnummer` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idtask`, `jobstatus_id`, `worker_personnummer`),
INDEX `fk_task_jobstatus1_idx` (`jobstatus_id` ASC),
INDEX `fk_task_worker1_idx` (`worker_personnummer` ASC),
CONSTRAINT `fk_task_jobstatus1`
FOREIGN KEY (`jobstatus_id`)
REFERENCES `bvsv_system`.`jobstatus` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_task_worker1`
FOREIGN KEY (`worker_personnummer`)
REFERENCES `bvsv_system`.`worker` (`personnummer`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
SQL script execution finished: statements: 15 succeeded, 1 failed
当我尝试添加链接这两个表的外键时出现此错误
CREATE TABLE IF NOT EXISTS `bvsv_system`.`worker` (
`personnummer` VARCHAR(45) NOT NULL,
`fornamn` VARCHAR(45) NULL DEFAULT NULL,
`efternamn` VARCHAR(45) NULL DEFAULT NULL,
`extraanstalld` VARCHAR(45) NOT NULL,
PRIMARY KEY (`personnummer`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
和
CREATE TABLE IF NOT EXISTS `bvsv_system`.`task` (
`idtask` INT(11) NOT NULL,
`attGora` VARCHAR(200) NULL,
`status` VARCHAR(45) NULL,
`to` VARCHAR(45) NULL,
`jobstatus_id` INT(11) NOT NULL,
`worker_personnummer` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idtask`, `jobstatus_id`, `worker_personnummer`),
INDEX `fk_task_jobstatus1_idx` (`jobstatus_id` ASC),
INDEX `fk_task_worker1_idx` (`worker_personnummer` ASC),
CONSTRAINT `fk_task_jobstatus1`
FOREIGN KEY (`jobstatus_id`)
REFERENCES `bvsv_system`.`jobstatus` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_task_worker1`
FOREIGN KEY (`worker_personnummer`)
REFERENCES `bvsv_system`.`worker` (`personnummer`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
帮助我的编码人员,将非常感谢! :)
答案 0 :(得分:2)
外键和主键需要具有完全相同的定义。 worker
表定义DEFAULT CHARACTER SET = latin1
。
我不确定为什么您要为不同的表使用不同的字符集。我建议只使用数据库默认值。
如果确实需要它们,则使字符集兼容。您可以在列级别执行此操作:
CREATE TABLE IF NOT EXISTS `task` (
`idtask` INT(11) NOT NULL,
`attGora` VARCHAR(200) NULL,
`status` VARCHAR(45) NULL,
`to` VARCHAR(45) NULL,
`jobstatus_id` INT(11) NOT NULL,
`worker_personnummer` VARCHAR(45) CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`idtask`, `jobstatus_id`, `worker_personnummer`),
INDEX `fk_task_jobstatus1_idx` (`jobstatus_id` ASC),
INDEX `fk_task_worker1_idx` (`worker_personnummer` ASC),
CONSTRAINT `fk_task_worker1`
FOREIGN KEY (`worker_personnummer`)
REFERENCES `worker` (`personnummer`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = InnoDB