Search code examples
mysqljoininner-join

MySQL query for summing values in another table


I have got a couple of tables with a parent child relationship. I want to apply a sum function to one column of child table and return it with all data of parent table for example.

Parent_table
ID, Date, Title

Child_table
ID, another_id, column_to_sum
//(ID is foreign key pointing to Parent_table)

Sample Data in Parent_table
1, 22-11-2010 00:00:00 , 'Some Title'
2, 13-11-2010 00:00:00 , 'Some Title 2'

Sample Data in Child_table
1, 1, 10
1, 2, 11
1, 8, 3
2, 5, 11
2, 8, 6

Output of the query should return all columns in parent_table with an additional column, that is, summing the values of column_to_sum in Child_table for each item in parent_table matched by ID.

How?


Solution

  •     SELECT p.ID,
          p.Date,
          p.Title,
          SUM(c.column_to_sum) Total
        FROM Parent_Table p LEFT JOIN
           Child_Table c ON p.ID = c.ID
        GROUP BY p.ID