database design for 'followers' and 'followings'?

后端 未结 4 1606
醉话见心
醉话见心 2020-12-23 00:01

Dear database experts/programmers:

I have a mysql table with users information, such as

id      user_id         name etc.
1       userA            
2         


        
相关标签:
4条回答
  • 2020-12-23 00:36

    Here is my design.

    Id    userId(PK)  followerId     followedDate         unfollewedDate
    1     123         456            YYYY-MM-DD HH:MI:SS  YYYY-MM-DD HH:MI:SS
    ...   ...         ...            ...                  ...
    

    I assumed userId - followerId combiation is unique. Dates can be useful. For example I'm thinking about to use if user unfollow and follow again in 5 minutes, it doesn't generate notification. I assume user made it by mistake. And I can analyze following statics by date.

    0 讨论(0)
  • 2020-12-23 00:39

    In general, your design is correct.

    But, if user_id is unique in the table "users", you don't need the column "id" in "users". (A single table containing a unique "id" and a unique "user_id" is pretty unusual.) You also don't need the column "id" in the table "followers".

    Primary key in "followers" should be (user_id, follower_id), and make sure each of those columns has a foreign key referencing "user_id" in "users".

    0 讨论(0)
  • 2020-12-23 00:44

    General tip. Use integers for ids rather than strings. There is a significant performance difference. So drop users.user_id, and rename users.id to users.user_id. Secondly your followers table should have indexes on user_id and follower_id. Again there is a significant performance benefit. I also like the idea of having a unique index on (user_id, follower_id), calling that your primary key, and dropping your id column.

    0 讨论(0)
  • 2020-12-23 00:45

    Yes, your design is the usual way of dealing with many-to-many relationships. Search for "modeling many-to-many database" and you will find lots of resources giving you examples of this.

    Add foreign keys from your relationship table to the users table.

    If your relationship involves additional information, you would put that as column in your connecting table. Maybe, for instance, the date when one user started following another.

    A separate surrogate key in the connecting table, like the ID column you have added, can be useful if you will want to have other tables reference your table.

    0 讨论(0)
提交回复
热议问题