我正在尝试为学校项目创建报纸系统,这是该代码的一部分。出于某种原因,我得到“错误代码:1215。无法添加外键约束”
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema nyheterhiof
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema nyheterhiof
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS nyheterhiof DEFAULT CHARACTER SET utf8 ;
USE nyheterhiof ;
-- -----------------------------------------------------
-- Table nyheterhiof.newspapers
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS nyheterhiof.newspapers (
newspaper_id INT(11) NOT NULL,
newspaper_name VARCHAR(45) NULL,
newspaper_city VARCHAR(45) NULL,
PRIMARY KEY (newspaper_id),
UNIQUE INDEX newspaper_id_UNIQUE (newspaper_id ASC))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table nyheterhiof.newspaper_Issues
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS nyheterhiof.newspaper_issues (
newspaper_issiue_id INT(11) NOT NULL,
newspaper_id VARCHAR(45) NOT NULL,
publication_date DATE NOT NULL,
comment VARCHAR(200) NULL,
PRIMARY KEY (newspaper_issiue_id),
UNIQUE INDEX newspaper_issiue_id_UNIQUE (newspaper_issiue_id ASC),
INDEX fk_newspaper_Issues_newspapers1_idx (newspaper_id ASC),
CONSTRAINT fk_newspaper_Issues_newspapers1
FOREIGN KEY (newspaper_id)
REFERENCES newspapers (newspaper_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
我尝试将FK移动到alter table语句,我尝试在“newspaper_issiues”中为newspaper_id添加索引。
答案 0 :(得分:1)
您已指定
CREATE TABLE IF NOT EXISTS nyheterhiof.newspapers (
newspaper_id INT(11) NOT NULL,
和
CREATE TABLE IF NOT EXISTS nyheterhiof.newspaper_issues (
...
newspaper_id VARCHAR(45) NOT NULL,
这就是问题所在。外键约束 MUST 两端的列在类型和宽度上匹配。
将newspaper_issues.newspaper_id
重新定义为 INT
,您将会很高兴。