简体   繁体   中英

Alter table to add a foreign key

I am using MySQL.

I have an existing table named school with hundreds of rows data be populated. Now I have another table named student , its primary key is " sid ".

I would like to alter my school table to have a foreign key reference to a student .

I tried the following sql statement:

ALTER TABLE school ADD FOREIGN KEY (sid) REFERENCES student(sid);

But I get error:

ERROR 1072 (42000): Key column 'sid' doesn't exist in table

What is the correct way to alter table to add a foreign key to another table?

You have to add the column sid on your table first.

ALTER TABLE school ADD COLUMN sid [INT, VARCHAR2(10];
ALTER TABLE school ADD FOREIGN KEY (sid) REFERENCES student(sid);

PS: I put [INT, VARCHAR2(10] because I don't know what type student(sid) is. Just change to the correct one.

where do you want to link your foreign key?

it seems that you missed the key to link against in the school table:

As far as i can imagine you want to link a student to his school.

So what i'd do is to add a column to the student table:

ALTER TABLE STUDENT
ADD COLUMN SCHOOL_ID INT NOT NULL;

then i'd create the foreign key in STUDENT table to point to SCHOOL

ALTER TABLE STUDENT
ADD FOREIGN KEY (F_SCHOOL_ID) REFERENCES SCHOOL(ID);

This is the best way and not the other way round.

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