You have the wrong database design, and you should take some time to read something about normalizing the database ( wikipedia / https://stackoverflow.com/a/166269/ ).
I assume your table looks something like this:
TABLE ================================ | group_id | user_ids | name | -------------------------------- | 1 | 1,4,6 | group1 | -------------------------------- | 2 | 4,5,1 | group2 |
therefore, in your user group table, each row represents one group and in the user_ids column you have a set of user IDs assigned to this group.
The normalized version of this table will look like this:
GROUP ===================== | id | name | --------------------- | 1 | group1 | --------------------- | 2 | group2 | GROUP_USER_ASSIGNMENT ====================== | group_id | user_id | ---------------------- | 1 | 1 | ---------------------- | 1 | 4 | ---------------------- | 1 | 6 | ---------------------- | 2 | 4 | ---------------------- | ...
Then you can easily select all users with an assigned group, or all users in a group, or all user groups, or whatever you think. In addition, your SQL query will work:
SELECT * FROM `group_user_assignment` WHERE user_id IN (1,2,3,4); SELECT * FROM `group_user_assignment` t1 JOIN `group` t2 ON t2.id = t1.group_id WHERE user_id IN (1,4); SELECT * FROM `group_user_assignment` t1 JOIN `group` t2 ON t2.id = t1.group_id WHERE t1.`user_id` = 1; SELECT * FROM `group_user_assignment` t1 JOIN `group` t2 ON t2.id = t1.group_id WHERE t1.`group_id` = 1; SELECT COUNT(*) AS `groups_count` FROM `group_user_assignment` WHERE `user_id` = 1; SELECT COUNT(*) AS `users_count` FROM `group_user_assignment` WHERE `group_id` = 1;
This way, it will be easier to update the database, if you want to add a new assignment, just just insert a new row in group_user_assignment , when you want to delete the assignment, you just delete the row in group_user_assignment .
In your database project, in order to update assignments, you will need to get your job set from the database, process it and update it, and then write it back to the database.
Here's sqlFiddle to play with.