duan0708676887 2010-04-27 18:36
浏览 80
已采纳

在PHP MySQL中处理多对多关系的最佳方法

I am looking for the best way to handle a database of many-to-many relationships in PHP and MySQL.

Right now I have 2 tables:

Users (id, user_name, first_name, last_name)
Connections (id_1, id_2)

In the User table id is auto incremented on add and user_name is unique, but can be changed. Unfortunately, I don't have control over the user_name and its ability to be changed, but I must account for it.

The Connections table is obviously, user1 and user2's id.

The connection table needs to account for these possible relations:

user1 --> user2 (user 1 friends with user 2 but not user2 friends with user1) 
user2 --> user1 (user 2 friends with user 1 but not user1 friends with user2) 
user1 <--> user2 (user 1 and user 2 mutually friends) 
user1 <-!-> user2 (user 1 and user 2 not friends) 

That part is not the problem, The problem I am having with is keeping these relations unique when and if they change in batches.

Possible solution 1: delete all of user 1's relations and readd them with the updated list. I think this might be too slow for my needs.

Solution 2? Anyone else encounter this problem? How should I best handle this?

update: distinguishing relationships:

i handle relationships like this:

user1, user2
user1, user3
user2, user1

in that example the following is true:
user1 follows user2 and user3
user2 only follows user1 but doesn't follow user3
user3 doesn't follow either user1 or user2

  • 写回答

1条回答 默认 最新

  • dongwen9947 2010-04-27 18:44
    关注

    You could use a compound primary key on Connections, using both columns (id_1, id_2) if you're having problems with uniqueness.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c