Adding a foreign key to a table

132 Views Asked by At

I haven't practised SQL in a while and I forgot how to add a foreign key to my table

    mysql> alter table students 
add foreign key fk_unit(unitid) 
references unit(unitid) 
on delete no action 
on update cascade;
    ERROR 1072 (42000): Key column 'unitid' doesn't exist in table

I'm wondering why this is the case? My unit table has a primary key called unitid, why does this keep happening?

3

There are 3 best solutions below

0
Ritesh Patel On

Try this one it should work....

ALTER TABLE students 
ADD CONSTRAINT FK_UnitId FOREIGN KEY (unitid)
    REFERENCES  unit(unitid);
0
zuchol On

Try this

ALTER TABLE Students
ADD FOREIGN KEY (unitid)
REFERENCES unit(unitid)
0
Sonam Gurung On

Your query is correct. Looks like field 'unitid' is missing from 'students' table or it has a different name.