Displaying null results for mysql related tables

Asked

Viewed 136 times

1

I need to create a relational query that returns records containing data from both the PERMISSAO table and the USUARIOS table. ALL PERMISSIONS records must be displayed. When there are no USER records, NULL must be displayed. The PERM_USU is used to relate the USUARIOS and PERMISSAO tables (in multi-schema for multiple). There is a condition, where PERM_USU.USUARIO_ID = 34

permission

  • id (int)
  • permission (varchar)

users

  • id (int)
  • user (varchar)

perm_usu

  • permission_id (int)
  • user_id (int)

I tried the query below, but it returns only the records that exist in Table 1 and Table 3.

select PERMISSAO.*, USUARIOS.* from PERMISSAO
left join PERM_USU on PERMISSAO.ID = PERM_USU.PERMISSAO_ID
left join USUARIOS on USUARIOS.ID = PERM_USU.USUARIO_ID
where PERM_USU.USUARIO_ID = 34

Thanks in advance for the help

  • Tried to trade left Join for only Join?

  • Well I tested here what I said above and it didn’t work...

  • I tried to replace the left Join with several other types of Join and the result was the same

  • Which bank are you using?

1 answer

1

You can use OUTER APPLY (with SQL Server) or a sub-query on Join (I think in other banks), something like that:

Using OUTER APPLY:

select
    p.*,
    oau.*
from
    PERMISSAO p
    outer apply(select
                    u.*
                from
                    USUARIOS u
                    inner join PERM_USU pu on (pu.usuario_id = u.id and pu.permissao_id = p.id)
                where
                    u.id = 34) oau

Using subconsulta in the Join:

select
    p.*,
    sq.id,
    sq.usuario
from
    PERMISSAO p
    left join ( select
                    pu.permissao_id,
                    u.*
                from
                    USUARIOS u
                    inner join PERM_USU pu on (pu.usuario_id = u.id)
                where
                    u.id = 34) sq on (sq.permissao_id = p.id)
  • I’ve tried that alternative, the result is the same. I remember that not all PERMISSION table Ids are in PERM_USU table, but I need them all to be displayed, leaving NULL (or empty) for when there is no

  • @Michelcurtirozatti, really was wrong, corrected my answer, see if now run. Note: in the first answer I had no bank to test.

Browser other questions tagged

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