MySQL交易和余额

时间:2018-10-24 10:26:00

标签: mysql sql stored-procedures triggers

所以我在MySQL中有此表,其中包含用户信息:

[             USERS           ]
[id | name |  email  | balance]
[ 1 | A    | a@e.com |    0   ]
[ 2 | B    | b@e.com |    0   ]
[ 3 | C    | c@e.com |    0   ]

和带有交易记录的表

[           TRANSACTIONS         ]
[id | user_id | product |  amount  | price ]
[ 1 |       3 |TV 600   |       1  | 279,22]
[ 2 |       2 |Radio G  |       1  |  32,12]

如果我在表transactions中添加一行,我想要的是该用户的balance也被更新。最好的做法是100%确保余额始终正确?

具有锁,触发器或其他东西的存储过程?

1 个答案:

答案 0 :(得分:0)

我将为该任务使用视图。保证了最新的数据,因为在查询视图时会执行其背后的查询,因此它会重新计算余额。

create view MyCalculatedView as
select u.id, u.name, u.email, t.balance from USERS u
left join (
    select user_id, sum(price) as balance
    from TRANSACTIONS
    group by user_id
) t on u.id = t.user_id;