I have 3 tables, User, Groups , and UserGroups.
UserGroups hold the User id_user and Group id_group.
User has id_user, and Group has id_group.
My question would be:
How do I pull data from all 3 tables to achieve the following:
- Listing All Groups in Group Table
- Listing Groups in the UserGroup Table that has been selected
- Listing Users that ARE NOT in UserGroups in the User Table.
- Listing Users that belong to a Group in the UserGroup Table.
I have the following SQL statements, but I would wish to combine them into 1 sql statement. Is it possible??
select * from grupos
and
SELECT DISTINCT usuarios.id_usuario
FROM usuarios
WHERE usuarios.id_usuario
NOT IN (SELECT DISTINCT id_usuario FROM usuarios_grupos)
Whereby, the first query displays:
Groups
- John
- Tim
- Jane
The 2nd query shows the following:
User
1. John
2. Jane
3. Tom
User Group
Empty
After selection of John:
User
2. Jane
3. Tom
User Group
1. John
Instead of having the following (which I have now):
User
1. John
2. Jane
3. Tom
After Selection of John:
UserGroup
1. John
Like what I have demonstrated above, if I select a Group and a User, and add it to User Groups. User Groups will display “Group, User” . (E.g. Development, Tom).
However, the Groups data table will still be shown as the following:
- Development
- Web
- Projects
The User data table will be “updated” instead:
- Tim
- Jane.
I tried the following, but I didn’t get the results I wanted:
SELECT grupos.id_grupo, usuarios.id_usuario
FROM usuarios_grupos
INNER JOIN
grupos
ON
usuarios_grupos.id_grupo = grupos.id_grupo
INNER JOIN
usuarios
ON
usuarios_grupos.id_usuario = usuarios.id_usuario
WHERE
usuarios.id_usuario
NOT IN (SELECT DISTINCT id_usuario FROM usuarios_grupos)
The simplest way to list the groups that have users belonging to them would be:
The simplest way to list the groups that don’t have users belonging to them would be:
EDIT: To list the Users that don’t belong in Groups, and all Groups that have Users in them, you can union the results of the queries that return each of these sets –
Or you can do this in a single query:
(This last query assumes that there is no overlap between group and user ID sets.)