[英]Implement Foreign Key in mysql table
Im trying to restore some old database tables, that when i build them i did not user foreign keys. 我试图还原一些旧的数据库表,当我建立它们时,我没有使用外键。 I have the field that corresponds to the Foreign Key, but i've not set it up in the relations table to which table it connected.
我有对应于外键的字段,但是我尚未在与其连接的表的关系表中进行设置。
Right know i have a problem because if i try to add that relation, it cannot, because there are some rows deleted in the other table. 正确知道我有一个问题,因为如果我尝试添加该关系,就不会出现问题,因为其他表中删除了一些行。
Is there any mysql command for checking this type NULL relations for me to delete the rows that i dont need.. and in the end.. add the relation. 是否有任何mysql命令来检查这种类型的NULL关系,以便我删除我不需要的行。最后,添加该关系。
TableA id, name TableB id, tableA_id, points
I've deleted some TableA rows.. now i cannot had that relation. 我已经删除了一些TableA行..现在我无法建立这种关系。
Any mysql command to help, or need to check manually? 任何mysql命令有帮助,还是需要手动检查?
Thanks 谢谢
Assuming that you have PRIMARY KEY
constraint at least on TableA.id
you can try 假设您至少在
TableA.id
上具有PRIMARY KEY
约束,则可以尝试
-- Delete all orphaned records from TableB
DELETE b
FROM tableb b LEFT JOIN tablea a
ON b.a_id = a.id
WHERE a.id IS NULL;
-- Create a FK constraint
ALTER TABLE TableB
ADD CONSTRAINT fk_a_id FOREIGN KEY (a_id) REFERENCES tablea(id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.