How do I relate three tables?

1

I have three tables.

NotethatifIperformanINNERJOINonallthreetables,Iwouldonlyreturnproduct1(Router),whichispresentinallthreetables.However,Iwouldneedhimtoreturnallresultstome,butwithoutrepeatinginformation.Ex.:

IfIhave7routersintheestoque1tableand9routersintheestoque2table,Iwouldneedthefinalresulttobe16routers.

Anditwouldalsoneedtoreturnallresultsthatwererelatedtothecadastro_produtostable.

Theexpectedresultwouldbe:

How can I proceed in this case?

    
asked by anonymous 10.08.2017 / 18:45

3 answers

5

you can do as follows:

Select
p.id,
p.nome,
sum(coalesce(e1.quantidade,0)+coalesce(e2.quantidade,0)) as Quantidade
from cadastro_produtos p
left outer join estoque1 e1 on e1.c_prod = p.id
left outer join estoque2 e2 on e2.c_prod = p.id
GROUP BY p.id, p.nome

But I advise you to remove one of the inventory tables, having only one: estoques where it would have one more column to identify which stock the item belongs to. Staying like this:

Product

id* | nome | 
1   | roteador |
2   | mouse |

Stock

estoque_id*|produto_id*|quantidade|responsavel
1          |    1      |     7    | fulano
1          |    2      |     1    | ciclano
1          |    6      |     3    | xxxxx
2          |    1      |     9    | xxxxx
    
10.08.2017 / 19:03
3

Try this, see if it suits what you want:

Select
p.id,
p.nome,
sum(coalesce(e1.quantidade,0)+coalesce(e2.quantidade,0)) as Quantidade
from cadastro_produtos p
left outer join estoque1 e1 on e1.c_prod = p.id
left outer join estoque2 e2 on e2.c_prod = p.id
GROUP BY p.id HAVING quantidade > 0

    
10.08.2017 / 19:06
0

Substitute INNER JOIN for FULL OUTER JOIN will solve your problem.

    
10.08.2017 / 18:49