MySQL - Error Code 1215, cannot add foreign key constraint

前端 未结 6 965
孤城傲影
孤城傲影 2020-12-11 18:04

i got these two succesfull queries:

create table Donors (
    donor_id int not null auto_increment primary key,
    gender varchar(1) not null,
    date_of_b         


        
6条回答
  •  无人及你
    2020-12-11 18:49

    To define a foreign key, the referenced parent field must have an index defined on it.

    As per documentation on foreign key constraints:

    REFERENCES tbl_name (index_col_name,...)

    Define an INDEX on condition_code in parent table Donors_Medical_Condition and it should be working.

    create table Donors_Medical_Condition (
        donor_id int not null,
        condition_code int not null,
        seriousness text,
    
        KEY ( condition_code ), -- <---- this is newly added index key
    
        primary key(donor_id, condition_code),
        foreign key(donor_id) references Donors(donor_id)    );
    

    But it seems you defined your tables order and references wrongly. You should have defined foreign key in Donors_Medical_Condition table but not in Donors_Medical_Conditions table. The latter seems to be a parent.

    Modify your script accordingly.

    They should be written as:

    -- create parent table first ( general practice )
    create table Medical_Conditions (
        condition_code int not null,
        condition_name varchar(50) not null,
        condition_description text,
        other_details text,
        primary key(condition_code)
    );
    
    -- child table of Medical_Conditions 
    create table Donors_Medical_Condition (
        donor_id int not null,
        condition_code int not null,
        seriousness text,
        primary key(donor_id, condition_code),
        foreign key(donor_id) references Donors(donor_id),
        foreign key(condition_code) 
            references Donors_Medical_Condition(condition_code)
    );
    

    Refer to:

    • MySQL Using FOREIGN KEY Constraints

    [CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

    reference_option:
    RESTRICT | CASCADE | SET NULL | NO ACTION

提交回复
热议问题