how to represent symmetric many to many relationship

后端 未结 5 934
盖世英雄少女心
盖世英雄少女心 2020-12-06 18:05

suppose i have a entity called USER and a relationship FRIENDSHIP exist between two USERs SO for that i have a table \'USER\' and a relationship table \'FRIENDSHIP\'

5条回答
  •  再見小時候
    2020-12-06 18:59

    If you did decide to use the symmetric design then it might be useful to ensure that every friendship is always bidirectional. You can try this:

    CREATE TABLE Friendship
     (UserId1 INT NOT NULL REFERENCES Users (UserId),
      UserId2 INT NOT NULL,
      PRIMARY KEY (UserId1, UserId2),
      FOREIGN KEY (UserId2, UserId1) REFERENCES Friendship (UserId1, UserId2));
    
    INSERT INTO Friendship (UserId1, UserId2)
    VALUES (1,2),(2,1);
    

提交回复
热议问题