简体   繁体   中英

Why Can't I form a foreign key on this?

I'am trying to add foreign key from department table to employee table. First one is done, But I can't create department table, it pops up error

ERROR 1005 (HY000): Can't create table `assignment`.`department` (errno: 150 "Foreign key constraint is incorrectly formed")

Like this.

CREATE TABLE employee
(
    First_Name VARCHAR(15) NOT NULL,
    Mid_Name CHAR,
    Last_Name VARCHAR(15) NOT NULL,
    SSN_Number CHAR(9) PRIMARY KEY NOT NULL,
    Birthday DATE,
    Address VARCHAR(50),
    Sex CHAR CHECK(Sex='M' OR Sex='F' OR Sex='m' OR Sex='f'),
    Salary Decimal(10,2) DEFAULT'800',
    Supervisor_SSN CHAR(9),
    Department_Number INT,
    CONSTRAINT fk_employee FOREIGN KEY(Supervisor_SSN)
    REFERENCES employee(SSN_Number) ON DELETE SET NULL
);

CREATE TABLE department
(
    Department_Name VARCHAR(15) NOT NULL UNIQUE,
    Department_Number INT PRIMARY KEY NOT NULL,
    Manaager_SSN CHAR(9) NOT NULL,
    Manager_Start_Date Date,
    CONSTRAINT fk_manager FOREIGN KEY(Manaager_SSN)
    REFERENCES employee(SSN_Number) ON DELETE SET NULL
);

I expect to add foreign key on Manaager_SSN to SSN_Number in employee table.

The option ON DELETE SET NULL is not valid if the column is declared NOT NULL . You're telling it to set the column to an impossible value.

So either change the declaration of Manaager_SSN to NULL , or change the foreign key to ON DELETE CASCADE . The former is probably more appropriate -- if the manager of a department leaves the company, you don't usually dissolve the department.

The foreign key definition includes

... ON DELETE SET NULL 
              ^^^^^^^^  

but the foreign key column is defined as non-NULL

 Manaager_SSN CHAR(9) NOT NULL,
                      ^^^^^^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM