MySQL 查询求和另一个表中的值

发布于 2024-10-05 06:44:06 字数 537 浏览 7 评论 0原文

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

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

如何?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

太阳男子 2024-10-12 06:44:06
    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
    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
好倦 2024-10-12 06:44:06

这并不能完全回答问题,但可能会对某人有所帮助,因为这是我的解决方案。 (我知道它缺少 JOIN)并且不知道该解决方案在大型数据库上的效率。

SELECT 
    Parent_table.*,
        (SELECT 
            SUM(Child_table.column_to_sum) 
        FROM Child_table 
        WHERE Child_table.id = Parent_table.id)
FROM Parent_table

This does not exactly answer the question, but might help someone since this was my solution. (I know it's missing the JOIN) And have no idea about the efficiency of this solution on a large DB.

SELECT 
    Parent_table.*,
        (SELECT 
            SUM(Child_table.column_to_sum) 
        FROM Child_table 
        WHERE Child_table.id = Parent_table.id)
FROM Parent_table
蓝色星空 2024-10-12 06:44:06

这超出了我的想象,但是怎么样?

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

This is off the top of my head, but how 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文