Skip to content
Advertisement

mysql error 1822 when trying to create new table with a FOREIGN KEY

trying the following code:

create table donation(
    donation_number int not null primary key  ,
    product_id int not null
);

create table stock ( 
    product_id int not null primary key, 
    available_qty int not null, 
    FOREIGN KEY (product_id ) REFERENCES donation(product_id)
);

Give back

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint ‘stock_ibfk_1’ in the referenced table ‘donation’.

Why? how can I solve this problem?

Advertisement

Answer

to create a foreign key relationship, the parent table column on which you are creating relation must be unique or primary and they must have the same datatype and size also

product_id in donation table is not unique.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement