mysql表中的多个外键到同一主键

时间:2022-07-18 11:30:33

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.

我有一个用户ID为主键的表用户。我有另一张名为Friends的桌子。在Friends表中,我有两个User作为朋友,由UserID和FrndID列表示,其中UserID和FrndID都应该是表user中的userID。

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.

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

1 个解决方案

#1


13  

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;

#1


13  

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;