mysql 一个表中的多个外键指向同一个主键

我有一个 user 表,其中 userID 作为主键.我有另一个名为 Friends 的表.在 Friends 表中,我有两个用户作为朋友,由 UserIDFrndID 列表示,其中 UserIDFrndID 应该是 user 表中的 userID.

I have a table user with userID as the primary key. I have another table called Friends. In the Friends table, I have two Users as friends represented by the columns UserID and FrndID where both UserID and FrndID should be a userID in table 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;

我想知道 REFERENCESusers(userId,userId) 是否多次正确引用一列?我没有创建 2 个单独的约束的原因是两个用户都必须存在于表 user 中.

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.

推荐答案

不,你应该创建两个外键:

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;

相关文章