How to use a relational database to store all users who belong to a group, and all groups which a user belongs to

database-designrelational-theory

This is a beginner question:

A user can belong to many groups, and a group can contain many users.

Let's say the two tables look something like this:

user_id
user_name
user_email

group_id
group_title
group_description

Where and how do I store all of the users which belong to a group and all the groups a user belongs to?

I can't imagine the groups table having a users field which contains comma separated user IDs being an acceptable solution. I think I get the basic concept of relational databases, but I'm not sure of the implementation. I get the one-to-one relationship, but I'm struggling with one-to-many. Is what I'm dealing with in this example two separate one-to-many relationships?

Best Answer

You want three tables for this:

  • Users with a row per user and whatever details you need
  • Groups with a row per group and whatever details you need
  • UsersGroups with a unique combination of UserId, GroupId that only keeps track of relationships

This will let you have as many combinations as you like.