具有相同ID的MySQL SUM [英] MySQL SUM with same ID

查看:239
本文介绍了具有相同ID的MySQL SUM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,我遇到了一个简单的问题,我只是学习PHP& MySQL,我已经使用谷歌搜索了一个多星期,但没有找到任何答案.

Sorry for the real simple question, I just learn PHP & MySQL, I already googling it for more than a week but I didn't found any answer.

我创建了一个简单的财务脚本,表格如下:

I create a simple finance script and the table is like below :

table_a
aid | value
1   | 100
2   | 50
3   | 150

table_b
bid | aid | value
1   | 1   | 10
2   | 1   | 15
3   | 2   | 5
4   | 2   | 10
5   | 3   | 25
6   | 3   | 40

我想要这样的结果

No | ID | Total | Balance
1  | 1  | 10    | 90
2  | 1  | 25    | 75
3  | 2  | 5     | 45
4  | 2  | 15    | 35
5  | 3  | 25    | 125
6  | 3  | 65    | 85

有人可以帮助我解决我的问题吗?

Can anybody help me with my problem?

谢谢

推荐答案

SELECT
   tb.bid as No,
   ta.aid as ID,
   tb.value as Total,
   ta.value-tb.total as Balance
FROM
  table_a AS ta
  INNER JOIN (
    SELECT
      tbx.aid AS aid,
      tbx.bid AS bid,
      tbx.value AS value,
      SUM(tby.value) AS total
    FROM 
      table_b AS tbx
      INNER JOIN table_b AS tby ON tby.aid=tbx.aid AND tby.bid<=tbx.bid
    GROUP BY tbx.bid
    ORDER BY tbx.bid
  ) AS tb ON tb.aid=ta.aid
ORDER BY tb.bid

正如@Quassnoi指出的那样,这对于MySQL来说不是很有效.我尝试使用怪胎连接而不是子查询,因为内部查询本身就可以使用.

As @Quassnoi pointed out, this is not very efficient with MySQL. I tried to use a freak join instead of a subquery, as the inner query might be of use in its own right.

修改

对此感兴趣,发现连接版本的速度是@Quassnoi的子查询版本的两倍……有人知道为什么会这样吗?

Took some interest in this and found the join version to be twice as fast as the subquery version by @Quassnoi ... anybody having an idea why this would be?

修改

回答第二个问题(在下面的评论中):

Answer to the second question (in comment below):

SELECT
  table_a.aid AS aid,
  SUM(table_b.value) AS Total,
  table_a.value-SUM(table_b.value) AS Balance
FROM
  table_a
  INNER JOIN table_b ON table_a.aid=table_b.aid
GROUP BY table_a.aid

这篇关于具有相同ID的MySQL SUM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆