Sum of values and display the result in a related table

3

I have two MySQL tables, the first with an id, name and the second with an id (related to the id of the first table) and a value. I need to make a query that adds all the values with the same id from table 2 and shows it in a new column of table 1, in the row of its related id.

Table 1:

id  |  nombre
1   |  silvia
2   |  maria
3   |  pedro

Table 2:

id  |  valores
1   |  4
1   |  7
2   |  51
2   |  6
3   |  9
3   |  14

Desired result:

id  |  nombre  |  valores sumados
1   |  silvia  |  11
2   |  maria   |  57
3   |  pedro   |  23
    
asked by Pablo García 14.06.2016 в 16:10
source

2 answers

4

You have to join the tables and group them by the data you want. So you can use the aggregation functions like SUM, AVG, etc.

Example:

SELECT a.id, a.nombre, SUM(b.valor)
   FROM tablanombres a LEFT JOIN tablavalores b ON a.id = b.id 
   GROUP BY a.id, a.nombre
    
answered by 14.06.2016 / 16:26
source
-1
select tabla1.nombre, sum(tabla2.valor) from tabla1, tabla2 where id_tabla1 = id_tabla2 group by tabla1.nombre, tabla2.valor

I could serve you like this without using joins

    
answered by 21.06.2018 в 17:48