How to design this Database part?

守給你的承諾、 提交于 2019-12-25 03:06:14

问题


I'm using PHP and MySQL.

I have a users table and a groups table. My question is, how can I implement a system in groups so that I can acces all the users id's which are part of that group.

Example: I have John, Mary and Alex in the users table. John is id 1, Mary is 2 and Alex is 3.

Now how can I add these users to the group users? I can't just add fields like "user_1", "user_2", "user_3". What if the group has 1000 members?


回答1:


You can have a groups table and users table. add groupid as foreign key in users table Like:

tbl_group : id: int(11) Auto Increment - P.K
          : group_name: varchar(500)

tbl_users : id: int(11) Auto Increment - P.K
          : user_name: varchar(20)
          : group_id:  int(11) - Foreign Key - // Foreign Key to groups Table.    

If you want many users want to join many groups then

tbl_group : id: int(11) Auto Increment - P.K
          : group_name: varchar(500)

tbl_users : id: int(11) Auto Increment - P.K
          : user_name: varchar(20)

tbl_user_group : id: int(11) Auto Increment - P.K
               : group_id:  int(11) - Foreign Key - // Foreign Key to groups Table.  
               : user_id:  int(11) - Foreign Key - // Foreign Key to usersTable.      



回答2:


you need another table that contains at least a user_id and a group_id

the relation between users and groups is m:n - a user can be part of multiple groups and a group can contain multiple users.




回答3:


You can add two Database tables:

tbl_users
id
group_id
name

AND

tbl_groups
id
name

save group id in the user table.




回答4:


Answer to support multiple groups for a user:

tbl_users
id
name

AND

tbl_groups
id
name

AND

tbl_user_groups
id
user_id
group_id

And thus we can have an n:n relationship (many users to many groups).



来源:https://stackoverflow.com/questions/20607955/how-to-design-this-database-part

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!