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

mysql Multiple Foreign Keys in a Table to the Same Primary Key(mysql 一个表中的多个外键指向同一个主键)
本文介绍了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;

这篇关于mysql 一个表中的多个外键指向同一个主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)