sql query: Get roles that do not belong to a user

1

I have the following tables:

La tabla usuarios con el campo Id
La tabla rol con el campo Id_rol
La tabla enlace con el campo Id_user y Id_rol

En la tabla usuarios tengo insertado a "pedro"
En la tabla rol tengo insertado "admin","usuario","moderador"
En la tabla enlace tengo insertado "pedro","usuario"

I want to get the ROLES that do not belong to the user "pedro"

I tried using the following sql query but I can not get the proper result:

SELECT ID_ROL
FROM enlacerole,usuariodef1
WHERE enlacerole.ID_USER=usuariodef1.CORREO and CORREO='pedro@'

union

SELECT ID_ROL
FROM roledef1
    
asked by EduBw 07.10.2017 в 22:15
source

2 answers

0

You can solve it with LEFT JOIN

SQL - Left join

The left join brings all the rows of the table on the left in addition to those that satisfy the join condition. For those that do not satisfy it, add null values in the columns of the table on the right.

What interests you is to take into account only when the user is 'pedro' and in turn get the rows where there is no matcheo with the table ENLACE , so you can first get the links from pedro and then take into account only the tuples that user_id is null to obtain the roles that do not belong to pedro.

Solution:

select * from rol left join (select * from enlace where id_user='pedro') as enlacespedro 
on (enlacespedro.id_rol = rol.id_rol) 
where id_user is null;

I created a test case here: SQL demo roles :

    
answered by 08.10.2017 / 05:33
source
0

Regards

By SQL I suggest the following:

Select * from Rol
WHERE 
   IdRol Not IN ( 
                  Select IdRol 
                  From Enlace 
                  Where 
                     IdUsr IN (Select IdUsr From Usuario WHERE Usuario='pedro')  
                )

I clarify that I'm using Usuario as the name of the column where you have the data compare, in your example you put that you insert pedro and then you look for pedro@ so apply it as it really corresponds.

    
answered by 07.10.2017 в 22:32