Left Join with multiple fields from the same table

Asked

Viewed 1,153 times

1

To build a lease, I have two tables.

The first is the contract, has some relationship fields as id_locador, id_locatario, id_fiador1, id_fiador2, among others. These fields are related to a table of people: id, nome, endereco, etc..

So all the people involved in the contract come from the same table "people".

How to make this relationship?

2 answers

5

What you need is something like, for every relationship of contrato with your table pessoa, you add a left join

select C.ID_CONTRATO, PT.NOME AS TITULAR, PR.NOME AS RESPONSAVEL, PN.NOME AS NOTA
from 
    CONTRATO C 
        LEFT JOIN PESSOA PT ON C.ID_PESSOA = PT.ID_PESSOA
        LEFT JOIN PESSOA PR ON C.ID_PESSOA_RESPONSAVEL = PR.ID_PESSOA
        LEFT JOIN PESSOA PN ON C.ID_PESSOA_NOTA = PN.ID_PESSOA

-1

When you make a left Join it will automatically give the results of that junction having lines or not, because the left Join it works as a junction of the tables but meeting its condition as if it were an or, if you want to get back more concise data use Inner Join

Browser other questions tagged

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