How to do trigger that implements this condition?

心不动则不痛 提交于 2019-12-11 17:24:37

问题


I need trigger that implements this process:

I should +add some number 50 to that user to table money where in table paym both columns table1 and table2 are not empty.

For example: User 'John' has both columns not empty and to him added 50 in table money.

Example in table below:

table: paym

 ID        username        table1        Table2  
+-------+-------------+-------------+-----------+
|   1   |  John       |  Value      |    Value  |
+-------+-------------+-------------+-----------+
|   2   |  Alex       |  Null       |    Null   |
+-------+-------------+-------------+-----------+

Table: money

 ID      username      total_money      
+-------+-------------+-------------+
|   1   |  John       |     50      | 
+-------+-------------+-------------+
|   2   |  Alex       |     0       |
+-------+-------------+-------------+

Query for this: (Not sure correct or not)

UPDATE 
 money
SET 
 money.total_money = money.total_money + 50
INNER JOIN 
 paym
ON
 money.username = paym.username
WHERE
   (paym.Table1 IS NOT NULL OR paym.Table1 <> '')
 AND
   (paym.Table2 IS NOT NULL OR paym.Table2 <> '')

回答1:


Here is a trigger for that purpose:

DELIMITER $$
CREATE trigger update_money_after_paym
AFTER INSERT ON paym
FOR EACH ROW
BEGIN
    IF (NEW.table1 IS NOT NULL AND NEW.table2 IS NOT NULL) THEN
        UPDATE money SET total_money = total_money + 50 WHERE username = NEW.username;
    END IF;
END;
$$
DELIMITER;

The code will run after each insert on table paym. If the newly inserted record has both columns table1 and table2 set to non-NULL values, then the trigger runs an UPDATE query that adds 50 to column total_money in table money for the record that has the same username as the newly inserted record in paym.



来源:https://stackoverflow.com/questions/55560450/how-to-do-trigger-that-implements-this-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!