I have the following two table scenario:
users
id groups
1 1,2,3
2 2,3
3 1,3
4 3
and
groups
id
1
2
3
How do I return the IDs of all users that belong to group 2 and 1 for example? Should I look into join, a helper group_membership table or function to separate the comma delimited group IDs to get something like this:
group_membership
user_id group_id
1 1
1 2
1 3
2 2
2 3
... ...
You should be having a many-to-many relationship between users and groups, (meaning, a user may belong into multiple groups, and a group can hold multiple users).
You do that by having 3 tables:
In the user_groups, you should have only 2 columns, user_id and group_id, each row is a single user belonging in a single group, where repititions on both sides are allowed.
Your example translates into:
Then, it’s very easy to query all of the users in specific groups, as well as all of the groups as user is in.
This process is also called Database Normalization