MySQL, selecting 4 related tables [closed]

0

I'm trying to do a select in 4 different tables. All are related. It all starts with ID_Morador .

SELECT morador.*
      ,unidades.*
      ,grupo.*
      ,condominios.*

  FROM morador
  LEFT JOIN unidades
    ON id_morador = morador.id_unidades,
  LEFT JOIN grupo
    ON id_grupo = morador.id_grupo,
  LEFT JOIN condominios
    ON id_condominios = morador.id_condominio

 WHERE morador.id_morador = '1';

Test online: link

    
asked by anonymous 18.12.2015 / 14:11

2 answers

1

I changed the SQL, at first I did not see the failure in jois , you're trying to left join everything with the morador table. I think the broker would be the SQL below, rename the aliases to what will best suit you.

    SELECT 
    m.*, a.*, b.*, c.*

FROM morador m

LEFT JOIN unidades      a   ON m.id_unidade       = a.id_unidades
LEFT JOIN grupo         b   ON a.ID_Grupo         = b.id_grupo
LEFT JOIN condominios   c   ON b.id_condominio   = c.ID_Condominios

WHERE
    m.ID_Morador = '1';

I tested your Fiddle with this SQL and it ran.

To use the alias in the columns you can not use the * you will have to list all the columns, which is also the most indicated.

SELECT 
    a.nome as uniNome, b.nome as grupNome

The fiddle is not working like this, but that's the way to do it, look at that link where there is an equal answer for your comment doubt.

    
18.12.2015 / 14:58
4

I think there are some syntax errors, try this.

SELECT 
    morador.*, unidades.*, grupo.*, condominios.*

FROM morador

LEFT JOIN unidades      ON ID_Morador       = morador.id_unidades
LEFT JOIN grupo         ON ID_Grupo         = morador.id_grupo
LEFT JOIN condominios   ON ID_Condominios   = morador.id_condominio

WHERE
    morador.ID_Morador = '1';
    
18.12.2015 / 14:33