本文介绍了MySQL查询对另一个表中的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几张有亲子关系的桌子.我想将sum函数应用于子表的一列,并返回它与父表的所有数据,例如.
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查询的输出应返回parent_table中的所有列以及一个附加列,即,将ID匹配的parent_table中每个项目的column_to_sum中的column_to_sum的值相加.
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.
如何?
推荐答案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
更多推荐
MySQL查询对另一个表中的值求和
发布评论