1
I needed to list, with SQL, a person’s father, mother and spouse along with their general data (e.g.: name, address, telephone, email, father, mother, spouse, status).
This data is in another dependent call table, each related to the person id
At first I thought it was very complicated, I even did searches on the internet, even here, without result, then I decided to burn the brain a little more, and I came to a super simple solution that satisfied my need:
SELECT
p.nome,
p.endereco,
p.telefone,
p.email,
dp.nome AS nomePai,
dm.nome AS nomeMae,
dc.nome AS conjuge,
p.status,
FROM
pessoa p
JOIN dependente dp ON dp.idPessoa = p.idPessoa AND dp.tipo = 6
JOIN dependente dm ON dm.idPessoa = p.idPessoa AND dm.tipo = 7
JOIN dependente dc ON dc.idPessoa = p.idPessoa AND dc.tipo = 5
Who knows a better way is just put there in the comments and help the community
And what exactly is your doubt?
– gmsantos
No doubt, I just wanted to share a solution to a problem
– Isaias Lima
This query doesn’t have much mystery... that’s right.
– Dirty Old Man
@Isaiasfile you can do the following: explains a little better what were the problems you faced and post the solution (using alias and multiple joins for the same table) as answer.
– gmsantos
The idea is for someone to do as you do: search for a particular issue on google or here and find your solution.
– gmsantos
Just note that you have a comma remaining at the end of their fields select that may cause error in query execution.
– Dirty Old Man
Yeah... that comma was nonchalant at the time of putting here on the site :)
– Isaias Lima