Update in a table with values from another

Asked

Viewed 375 times

2

How to update the values of a table, using values taken from another table:

UPDATE produto -- atualizar a tabela produto 
   SET produto.quant = SUM(entrada.quant) --  produto.quant será igual a soma da coluna quant da tabela entrada
 WHERE produto.id = entrada.idproduto -- onde produto.id = entrada.idproduto

Product table:

id int
descricao string
tipo string
quant int

Input table

id int
idProduto int
data date
quant int

1 answer

3


You can set the value of quant of the product, based on other consultation, please note how would you look:

UPDATE produto
   SET produto.quant =
       (SELECT SUM(entrada.quant)
          FROM entrada
         WHERE produto.id = entrada.idproduto)

I made an example at Sqlfinddle, if you want to verify.


I made a change, I couldn’t simulate the problem reported in the comments, so I made a change:

UPDATE produto
   SET produto.quant =
       (SELECT SUM(IFNULL(entrada.quant,0))
          FROM entrada
         WHERE produto.id = entrada.idproduto);

Example with the structure of your tables in Sqlfinddle.

  • error 1048: Column 'Quant' cannot be null

  • before you ask. I have no null value in the Quant column of any of the tables. which may be?

  • Do you have any record in the entry table ?

  • @Maurivan does. David, changed

  • @Italorodrigo, take a look at the change I made.

  • @David still made the same mistake :/

  • 1

    thanks for the help, but I decided to make the code by the application itself instead of by the query.

Show 2 more comments

Browser other questions tagged

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