Inner join join table with several equal IDs

1

The problem is as follows, I have two tables one of contracts and one of borrowers 1xN and when I do inner join it repeats exactly the amount of columns that I have in borrower but only brings the name of the first one. follows an example:

select 
    co.id,
    ....
form 
   contratos ct
inner join
   os ss on (ss.contratos_id=ct.id)
inner join
   mutuarios mt on (mt.contratos_id=ct.id)
where....

I hope you can help me.

    
asked by anonymous 14.10.2015 / 21:32

2 answers

1

This is the normal behavior of a INNER JOIN it associates the records in one table with those in the other.

If in the contratos table you have 1 record and in the borrowers 10 records linked to that contrato , a inner join between them will show 10 records repeating the fields that you placed referring to the contracts table

In your query, you are using an alias that has not been defined co. in your tables from

In your case, you have INNER JOIN between three tables, so the number of records will be the equivalence between them. In your specific case, if you have 1 contract, 3 os of that contract and 3 mutuários of this contract you should see 9 records. That is the combination of the three tables:

See this example: link

You will see that for each record of A (in the example) the combination of B and C

If you want only the contract to appear, without specifying any of the records that are duplicates, use the DISTINCT clause in your query:

select DISTINCT
    ct.id,
    ....
from
   contratos ct
inner join
   os ss on (ss.contratos_id=ct.id)
inner join
   mutuarios mt on (mt.contratos_id=ct.id)
where....

It's important to remember that DISTINCT will only delete duplicates for the scope of the select columns, ie ct.id, ....

    
14.10.2015 / 21:51
0

In fact the mistake was mine, I was grouping and could not see the other borrowers. Thank you all for your attention.

    
15.10.2015 / 22:45