我有几张有父子关系的 table 。例如,我想将 sum 函数应用于子表的一列,并将其与父表的所有数据一起返回。

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 中的所有列和一个附加列,即对 parent_table 中 ID 匹配的每个项目的 column_to_sum 中的 Child_table 值求和。

如何?

最佳答案

    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 查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4337993/

10-11 02:46
查看更多