为什么我不能添加这个外键约束?

时间:2017-06-01 04:22:26

标签: mysql sql database

我很沮丧。我无法为表Test_info添加外键约束:

FOREIGN KEY Test_info(score) REFERENCES Test(score)

它一直给我错误1215无法添加外键约束。我确定数据类型是相同的,以及名称等......任何人?

整个SQL表的创建是:

CREATE TABLE IF NOT EXISTS Employees    (
    ssn VARCHAR(20),
    union_mem_no VARCHAR(20),
    PRIMARY KEY (ssn)
) ENGINE=INNODB;

CREATE TABLE IF NOT EXISTS Traffic_Control  (
    ssn VARCHAR(20),
    exam_date DATE,
    PRIMARY KEY (ssn),
    FOREIGN KEY (ssn) REFERENCES Employees(ssn) ON DELETE CASCADE
) ENGINE=INNODB;

CREATE TABLE IF NOT EXISTS Technician   (
    ssn VARCHAR(20),
    T_name VARCHAR(20),
    phone_num VARCHAR(20),
    address VARCHAR(50),
    Salary INT,
    PRIMARY KEY (ssn),
    FOREIGN KEY (ssn) REFERENCES Employees(ssn) ON DELETE CASCADE
) ENGINE=INNODB;

CREATE TABLE IF NOT EXISTS Model (
    model_no VARCHAR(20),
    Capacity INT,
    Weight INT,
    PRIMARY KEY (model_no)
) ENGINE=INNODB;

CREATE TABLE IF NOT EXISTS Expert   (
    ssn VARCHAR(20),
    model_no VARCHAR(20),
    FOREIGN KEY (ssn) REFERENCES Technician(ssn) ON DELETE CASCADE,
    FOREIGN KEY (model_no) REFERENCES Model(model_no) ON DELETE CASCADE
) ENGINE=INNODB;

CREATE TABLE IF NOT EXISTS Plane (
    reg_no VARCHAR(20),
    PRIMARY KEY (reg_no)
) ENGINE=INNODB;

CREATE TABLE IF NOT EXISTS Type (
    reg_no VARCHAR(20),
    model_no VARCHAR(20),
    FOREIGN KEY (reg_no) REFERENCES Plane(reg_no),
    FOREIGN KEY (model_no) REFERENCES Model(model_no)
) ENGINE=INNODB;

CREATE TABLE IF NOT EXISTS Test (
    FAA_no VARCHAR(20),
    T_name VARCHAR(20),
    score INT,
    PRIMARY KEY (FAA_no)
) ENGINE=INNODB;

CREATE TABLE IF NOT EXISTS Test_info    (
    ssn VARCHAR(20),
    FAA_no VARCHAR(20),
    T_date DATE NOT NULL,
    hours INT,
    score INT,
    PRIMARY KEY (ssn, FAA_no),
    FOREIGN KEY (ssn) REFERENCES Employees(ssn) ON DELETE CASCADE,
    FOREIGN KEY (FAA_no) REFERENCES Test(FAA_no),
    FOREIGN KEY (score) REFERENCES Test(score)
) ENGINE=INNODB;

1 个答案:

答案 0 :(得分:1)

您必须在您引用的列上定义UNIQUE约束,以便能够为该列创建外键关系。

但是,从您的数据架构看,score列可能没有唯一值。

由于您已经与Test表的主键(FAA_no)建立了外键关系,因此我没有看到添加第二个外键的重点。< / p>