mysql 一个表中的多个外键指向同一个主键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18839599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mysql Multiple Foreign Keys in a Table to the Same Primary Key
提问by Bill Karwin
I have a table userwith userIDas the primary key. I have another table called Friends. In the Friendstable, I have two Users as friends represented by the columns UserIDand FrndIDwhere both UserIDand FrndIDshould be a userIDin table user.
我有一个表user与userID作为主键。我还有一张桌子叫Friends. 在Friends表中,我有两个用户的朋友表示由列UserID和FrndID其中两个UserID和FrndID应该是一个userID表user。
I want to enforce data integrity. Could I use something like this?
我想强制执行数据完整性。我可以使用这样的东西吗?
ADD CONSTRAINT `ufd_users_fk` FOREIGN KEY (`userId`, `friendId`)
REFERENCES `users` (`userId`, `userId`) ON DELETE CASCADE ON UPDATE CASCADE;
I want to know is REFERENCESusers(userId,userId)referencing a column multiple times correctly? The reason I am not creating 2 separate constraints, is that both users must exist in table user.
我想知道REFERENCES用户(userId ,userId)是否正确多次引用一列?我没有创建 2 个单独的约束的原因是两个用户都必须存在于 table 中user。
回答by Bill Karwin
No, you should create two foreign keys:
不,您应该创建两个外键:
ADD CONSTRAINT `ufd_users_fk` FOREIGN KEY (`userId`)
REFERENCES `users` (`userId`)
ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `ufd_users_fk` FOREIGN KEY (`friendId`)
REFERENCES `users` (`userId`)
ON DELETE CASCADE ON UPDATE CASCADE;

