将一个对象连接到其他相同类型的对象时,我应该使用 1:n 还是 m:n 关系?

Should I be using a 1:n or m:n relation when connecting an Object to other Objects of the same type?

这是关于 SQL(Oracle PL/SQL 如果有区别的话)。

我有一个用户类型的自定义对象。一个用户有两列:

他的朋友是其他用户。我想在这里使用嵌套的 table,但我想知道:这是 1:n 还是 m:n 关系?我认为这可以用 1:n 建模,因为这 n 个用户中的每一个本身都有 n 个其他连接。

据推测,以下是正确的:

  • 一个用户可以有多个朋友。
  • 一个用户可以成为多个其他用户的朋友。

这使得这是一种 n:m 关系。

实现这种关系的推荐方法是使用 association/junction table。另外,我也会推荐ids。该模型看起来像:

create table users (
    user_id int generated always as identity primary key,
    name varchar2(255)
    createdAt date not null
);

create table friends (
    friend_id int generated always as identity primary key,
    user_1 int not null references users(user_id),
    user_2 int not null references users(user_id),
    unique (user_1, user_2),
    createdAt date not null
);

我不推荐嵌套的 tables。它们不是为参照完整性而设计的。