How to make SQL many-to-many same-type relationship table

前端 未结 4 1983
深忆病人
深忆病人 2020-11-27 17:19

I\'m a newbie to SQL and I\'m jumping in head first trying to learn as much as possible as I\'m coding, which is difficult as I\'m designing the database I\'ll have to live

4条回答
  •  抹茶落季
    2020-11-27 17:39

    You should use the ID's of the two users as PRIMARY KEY in a relationship table (the relation would be unique even if not bi-directional). Something like that

    CREATE TABLE Users ( id int(9) NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (id) );

    CREATE TABLE Relationships ( id1 int(9) NOT NULL, id2 int(9) NOT NULL, friended TIMESTAMP NOT NULL, PRIMARY KEY (id1, id2) );

    Please note:

    • id1 and id2 reference Users table (the code above was very simplified)
    • even if the relationship is not "bi-directional" you can think that if you have id1 - id2 it seems that id1 user add id2 user as a friend but not necessarily the opposite - THEN id2 user can add id1 user as friend - in the table of relationships you can have these possible combinations:
      • id1-id2, (only 1 add 2 as a friend)
      • id2-id1, (only2 add 1 as a friend)
      • id1-id2 AND id2-id1 (both - it means 2 lines in relationships table, and both are MUTUAL friends)

提交回复
热议问题