id到一个字段的两列的总和

时间:2013-11-20 08:52:10

标签: mysql sql codeigniter phpmyadmin

我需要通过id将两列的总和加到一个具有相同id的字段

例如:我希望余额为income - expenses = balance

表格交易:

=========================================================
|  id  | idBudget  |  expenses      ||      income      |
=====+========+===============+=====|=====+========+====|
|   1  |      2    |     10         ||        0         |  
|----+--------+---------------+-----||----+--------+----|
|   2  |      3    |     200        ||        0         |              
|----+--------+---------------+-----||----+--------+----|
|   3  |      2    |     1          ||     100          |  
|----+--------+---------------+-----||----+--------+----|
|   4  |      2    |     0          ||     1000         |              
|----+--------+---------------+-----||----+--------+----|

表格预算:

=====================================
|  idBudget        |  Balance       |
=====+========+===============+=====|
|     2            |     1090       |
|----+--------+---------------+-----|
|     3            |     -200       |
|----+--------+---------------+-----|

我厌倦了使用触发器,但我想我不知道如何实现它

2 个答案:

答案 0 :(得分:1)

CREATE TABLE starting_balance AS (SELECT * FROM budget);

DROP TABLE budget;

CREATE VIEW budget AS (
    SELECT
        sb.idBudget,
        sb.balance + SUM(t.income - t.expenses) AS balance
    FROM starting_balance sb
    LEFT JOIN transactions t ON (t.idBudget = sb.idBudget)
    GROUP BY
        sb.idBudget,
        sb.balance
);

换句话说,使用视图而不是表。您可以不时更新起始余额(并删除或标记您不再需要的交易!),您可以使用物化视图。

答案 1 :(得分:0)

这样的东西?

INSERT INTO Budget(SELECT idBudget, SUM(income)-SUM(expenses) as Balance
FROM Transactions GROUP BY idBudget )

delimiter //
CREATE TRIGGER balance AFTER INSERT  ON Transactions
FOR EACH ROW
BEGIN
INSERT INTO Budget(SELECT NEW.idBudget, SUM(NEW.income)-SUM(NEW.expenses) as Balance
    FROM Transactions GROUP BY idBudget )
END;
delimiter ;