简体   繁体   中英

Database trigger How to insert sum of values, from one table to another?

I think best way is Triggers? Any idea?

I should insert sum of payment_amount seperately for each username from table Payments , to total_money table total_balance It should be inserted automaticly every time when new velues inserted to table Payments

For example: User "John" filled his account 2 time 100$ and 50$, Total in his account 150$

Example in tables:

Table: Payments

 ID      username     payment_amount    Status  
+-------+-------------+-------------+-----------+
|   1   |  John       |     100     | Complete  |
+-------+-------------+-------------+-----------+
|   2   |  John       |     50      | Complete  |
+-------+-------------+-------------+-----------+
|   3   |  Alex       |     100     | Complete  |
+-------+-------------+-------------+-----------+

Table: total_balance

 ID      username      total_money      
+-------+-------------+-------------+
|   1   |  John       |     150     | 
+-------+-------------+-------------+
|   2   |  Alex       |     100     |
+-------+-------------+-------------+

I'd recommend not to keep redundant data. That is likely a recipe for desaster when inconsistencies occur. I suggest you use a view, that gives you the sums.

DROP TABLE total_balance;

CREATE VIEW total_balance
AS
SELECT p.username,
       sum(p.payment_amount) total_money
       FROM payments p
       GROUP BY p.username;

Or, if you only want to sum completed payments:

DROP TABLE total_balance;

CREATE VIEW total_balance
AS
SELECT p.username,
       sum(p.payment_amount) total_money
       FROM payments p
       WHERE p.status = 'Complete'
       GROUP BY p.username;

The figures in the view will always be accurate and reflect the current situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM