1
I have a stock movement table with the following columns and data:
table moves
id | operacao | prodinsumo | qtde
----------------------------------
1 | 1 | 25 | 6
2 | 2 | 10 | 3
3 | 10 | 17 | 1
4 | 11 | 10 | 2
table inputs:
codinsumo | nomeinsumo
------------------------
10 | água mineral
table products:
codproduto | nomeproduto
---------------------------
25 | refrigerante
17 | espetinho
In the column operacao
are stored the codes of the operations that are:
1 - Product sale
2 - Sale Insumo
10 - Estorno Product
11 - Estorno Insumo
The column prodinsumo
stores the input code or the product according to the operation.
I would like to be able to do a query that puts the name of the input or product according to the operation, but I do not know how to do.
Here is a query I made that serves to select the columns but does not decide which table will get the name, whether it is of inputs or products.
select
case m.operacao
when 1 then "Venda produto"
when 2 then "Venda insumo"
when 10 then "Estorno produto"
when 11 then "Estorno insumo"
end as operacao,
i.nomeinsumo as nome, -- ou p.nomeproduto as nome
m.qtde
from movimentacoes m
left join produtos p on m.prodinsumo = p.codproduto
left join insumos i on m.prodinsumo = i.codinsumo
I need that when the column operacao
have the values 1
or 10
the column nome
either with the column value nomeproduto
table produtos
and when you have the values 2
or 11
either with the column value nomeinsumo
table insumos
.
Put your schema in sqlfiddle, so help us already send you the ready query. But finally, to use this logic, you can use https://dev.mysql.com/doc/refman/5.7/en/case.html when the value is x, make a subselect, if not another.
– juniorb2ss