gpt4 book ai didi

database - 是否有一种优雅的方式来存储双重关系(即用户 1 和用户 2 是 friend )

转载 作者:太空狗 更新时间:2023-10-30 01:50:59 25 4
gpt4 key购买 nike

这个月我在两份不同的工作中遇到了同样的问题:

Version 1: User 1 & User 2 are friends
Version 2: Axis 1 & Axis 2 when graphed should have the quadrants colored...

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

有两种明显的方法:

方法一:

store the information twice (i.e. two db rows rows per relationship):
u1, u2, true
u2, u1, true
u..n, u..i, true
u..i, u..n, true

have rules to always look for the inverse on updates:
on read, no management needed
on create, create inverse
on delete, delete inverse
on update, update inverse

Advantage: management logic is always the same.
Disadvantage: possibility of race conditions, extra storage (which is admittedly cheap, but feels wrong)

方法二:

store the information once (i.e. one db row per relationship)
u1, u2, true
u..n, u..i, true

have rules to check for corollaries:
on read, if u1, u2 fails, check for u2, u1
on create u1, u2: check for u2, u1, if it doesn't exist, create u1, u2
on delete, no management needed
on update, optionally redo same check as create

Advantage: Only store once
Disadvantage: Management requires different set of cleanup depending on the operation

我想知道是否有第三种方法遵循“使用 f(x,y) 的键,其中 f(x,y) 对于每个 x,y 组合都是唯一的,并且其中 f(x,y) === f(y,x)"

我的直觉告诉我,应该有某种按位运算的组合可以满足这些要求。像两列的东西:

key1 = x && y键2 = x + y

我希望那些花更多时间在数学系而不是社会学系的人已经看到了这种可能性或不可能的证据,并且可以提供一个快速的“[你这个白痴,]它很容易证明(im)可能,请参阅此链接”(名称调用可选)

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

谢谢

最佳答案

还有一种方法可以通过添加额外的约束来使用第二种方法。检查 u1 < u2 :

CREATE TABLE User
( Name VARCHAR(10) NOT NULL
, PRIMARY KEY (Name)
) ;

CREATE TABLE MutualFriendship
( u1 VARCHAR(10) NOT NULL
, u2 VARCHAR(10) NOT NULL
, PRIMARY KEY (u1, u2)
, FOREIGN KEY (u1)
REFERENCES User(Name)
, FOREIGN KEY (u2)
REFERENCES User(Name)
, CHECK (u1 < u2)
) ;

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

关于database - 是否有一种优雅的方式来存储双重关系(即用户 1 和用户 2 是 friend ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8808994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com