MySQL query to sum values ​​in another table

I have a couple of tables with parent relationships with a daughter. I want to apply the sum function to one column of a child table and return it with all the data in the 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

The query result should return all columns in parent_tablewith an additional column, that is, sum the values column_to_sumin Child_tablefor each element in parent_table, matched by identifier.

How?

+3
source share
2 answers
    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
+3
source

This is from the top of the head, but what about

SELET p.ID,
  p.Date,
  p.Title,
  SUM(c.column_to_sum) Total
FROM Parent_Table p INNER JOIN
   Child_Table c ON p.ID = c.ID
GROUP BY p.ID,
      p.Date,
      p.Title
+2
source

Source: https://habr.com/ru/post/1778154/


All Articles