Mysql/PHP - Compare two lists and filter information

Asked

Viewed 89 times

0

This is a matter of ENEM (jokes aside, let’s doubt). The answer may be in Mysql or in PHP.

I need to do a search where I list all permissions that the user does not have. For this I have the following tables:

sys_perfil_permissions

CREATE TABLE `sys_perfil_permissoes` (
    `id_perfil_permissao` INT(11) NOT NULL AUTO_INCREMENT,
    `id_perfil` INT(11) NULL DEFAULT NULL,
    `id_funcionalidade` INT(11) NULL DEFAULT NULL,
    `permissao` VARCHAR(20) NULL DEFAULT NULL,
    PRIMARY KEY (`id_perfil_permissao`)
)

sys_user_permissions

CREATE TABLE `sys_usuario_permissoes` (
    `id_usuario_permissao` INT(11) NOT NULL AUTO_INCREMENT,
    `id_usuario` INT(11) NULL DEFAULT NULL,
    `id_perfil_permissao` INT(11) NULL DEFAULT NULL,
    `permissao` INT(4) NULL DEFAULT NULL,
    PRIMARY KEY (`id_usuario_permissao`)
)

The sys_perfil_permissions table functions as a default, when creating a user, it already has some permissions by default, when I save these permissions from the user, they are saved in the sys_user_permissions table.

How can I find permissions that the user does not have in a SELECT?

On the screen, it would look like this: inserir a descrição da imagem aqui

1 answer

3


Use on SELECT the method WHERE NOT EXISTS() passing another SELECT in with the conditions. Example:

SELECT 
   t.id
FROM 
   teste as t                      
WHERE NOT EXISTS 
   (SELECT * FROM permissoes as p
    WHERE 
      p.teste_id = t.id);

Then the result will be all that do not exist in the table there that I used of example.

  • Then I’ll have to select from the same table?

  • Or would you be like this? 
SELECT * FROM sys_perfil_permissoes pp
JOIN sys_funcionalidades f ON pp.id_funcionalidade = f.id_funcionalidade
WHERE EXISTS (SELECT * FROM sys_usuario_permissoes up2 WHERE up2.id_funcionalidade = pp.id_funcionalidade
AND up2.id_usuario = 660 )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.