[英]Alter table to add a foreign key
I am using MySQL. 我正在使用MySQL。
I have an existing table named school
with hundreds of rows data be populated. 我有一个名为school
的现有表,其中填充了数百行数据。 Now I have another table named student
, its primary key is " sid ". 现在我有另一个名为student
表,它的主键是“ sid ”。
I would like to alter my school
table to have a foreign key reference to a student
. 我想改变我的school
表,以便为student
提供外键参考。
I tried the following sql statement: 我尝试了以下sql语句:
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. 您必须先在表格上添加列sid
。
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. PS:我把[INT, VARCHAR2(10]
因为我不知道学生(sid)是什么类型。只需改为正确的。
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 然后我在STUDENT表中创建外键指向SCHOOL
ALTER TABLE STUDENT
ADD FOREIGN KEY (F_SCHOOL_ID) REFERENCES SCHOOL(ID);
This is the best way and not the other way round. 这是最好的方式,而不是相反。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.