在mysql中求和多行

时间:2017-03-27 05:40:06

标签: php mysql

我有一个mysql表名请求,请求包含以下字段

id mem_id amount status rtype
1   11     200     0     ph
2   12     200     0     ph
3   13     400     0     ph
4   14     200     0     ph
5   15     300     0     ph

我想用这个表做的是,如果用户插入另一个数据并且rtype = gh和amount = 600我希望mysql从请求表中选择并总结金额以获得新请求的数量,这是600像对等捐赠一样

结果可能看起来像

id mem_id amount status rtype
1   11     200     0     ph
2   12     200     0     ph
4   14     200     0     ph

id mem_id amount status rtype
1   11     200     0     ph
3   13     400     0     ph

我有这个查询,但它从我的phpmyadmin

返回一个空结果
SELECT id, mem_id, SUM(amount), status, rtype FROM tbl_request WHERE rtype = 'ph' AND status = 0 AND amount = 6000 GROUP BY id;

请任何帮助

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以使用mysql变量进行累积求和。

SELECT 
    *
FROM
    (SELECT @var:=600) a,
    (SELECT 
        tbl_request.*,
            if((@var:=@var - amount) > 0, amount, amount + @var) as my_amount
    FROM
        tbl_request 
    WHERE
        rtype = 'ph' AND status = 0
    ORDER BY amount ASC) AS b
WHERE
    my_amount > 0

Result

从这里开始:https://stackoverflow.com/a/11935359/6124896