数据库 – 是否有一种优雅的方式来存储双重关系(即用户1和用户2是朋友)

前端之家收集整理的这篇文章主要介绍了数据库 – 是否有一种优雅的方式来存储双重关系(即用户1和用户2是朋友)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我本月在两个不同的工作中遇到了同样的问题:
  1. Version 1: User 1 & User 2 are friends
  2. Version 2: Axis 1 & Axis 2 when graphed should have the quadrants colored...

问题是,我没有看到使用RDBMS来存储和查询此信息的优雅方式.

有两种明显的方法

方法1:

  1. store the information twice (i.e. two db rows rows per relationship):
  2. u1,u2,true
  3. u2,u1,true
  4. u..n,u..i,true
  5. u..i,u..n,true
  6.  
  7. have rules to always look for the inverse on updates:
  8. on read,no management needed
  9. on create,create inverse
  10. on delete,delete inverse
  11. on update,update inverse
  12.  
  13. Advantage: management logic is always the same.
  14. Disadvantage: possibility of race conditions,extra storage (which is admittedly cheap,but feels wrong)

方法2:

  1. store the information once (i.e. one db row per relationship)
  2. u1,true
  3.  
  4. have rules to check for corollaries:
  5. on read,if u1,u2 fails,check for u2,u1
  6. on create u1,u2: check for u2,if it doesn't exist,create u1,u2
  7. on delete,no management needed
  8. on update,optionally redo same check as create
  9.  
  10. Advantage: Only store once
  11. Disadvantage: Management requires different set of cleanup depending on the operation

我想知道是否有第三种方法沿着“使用f(x,y)的关键线,其中f(x,y)对于每个x,y组合是唯一的,y)=== F(Y,X)”

我的直觉告诉我应该有一些可以满足这些要求的按位运算组合.类似于两列的东西:

key1 = x&& ÿ
key2 = x y

我希望那些花更多时间在数学系的人,以及更少的时间在社会学系已经看到了这种可能性或不可能性的证据,并且可以提供一个快速的“[你好白痴],它很容易被证明(即时通讯)可能,请看这个链接“(名字叫可选)

任何其他优雅的方法也将非常受欢迎.

谢谢

解决方法

还有一种方法可以通过添加额外约束来使用第二种方法.检查u1< U2:
  1. CREATE TABLE User
  2. ( Name VARCHAR(10) NOT NULL,PRIMARY KEY (Name)
  3. ) ;
  4.  
  5. CREATE TABLE MutualFriendship
  6. ( u1 VARCHAR(10) NOT NULL,u2 VARCHAR(10) NOT NULL,PRIMARY KEY (u1,u2),FOREIGN KEY (u1)
  7. REFERENCES User(Name),FOREIGN KEY (u2)
  8. REFERENCES User(Name),CHECK (u1 < u2)
  9. ) ;

读取,创建,插入或更新的规则必须使用(LEAST(u1,GREATEST(u1,u2)).

猜你在找的MsSQL相关文章