I have user and group tables set up as the following.
users
id int
groups
id int
users_groups
user_id int
group_id int
Example data:
+---------+----------+
| user_id | group_id |
+---------+----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 3 | 2 |
| 3 | 3 |
| 4 | 1 |
| 4 | 2 |
| 5 | 2 |
+---------+----------+
Is there a way to select all users who are not in a given group? I tried joining the users and users_groups tables and adding a, say, group_id != 1 condition, but I end up getting the user when they are in another group, e.g., users [1, 3, 3, 4, 5].
So when I say I want users who are not in a given group, group_id != 1 in this case, the example results should be users [3, 5].
The simplest way to select the id of the users not in a given group is to use
NOT IN:Other commonly used alternatives are
NOT EXISTS:And
LEFT JOIN / IS NULL: