2016-03-25 68 views
0

我正在爲一個學校項目創建一個報紙系統,這是該代碼的一部分。出於某種原因,我得到「錯誤代碼:1215無法添加外鍵約束」外鍵不「工作」?

-- MySQL Workbench Forward Engineering 

SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0; 
SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; 
SET @[email protected]@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 statment,我曾嘗試添加索引中「newspaper_issiues」到newspaper_id。

回答

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, 

這就是問題所在。外鍵約束必須兩端的列匹配類型和寬度

重新定義newspaper_issues.newspaper_idINT你會很好去。

+0

神聖的地獄,我怎麼錯過了!太好了,謝謝! –