MySQL查询对另一个表中的值求和 [英] MySQL query for summing values in another table
本文介绍了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查询对另一个表中的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文