UPDATE Same Row After UPDATE in Trigger

后端 未结 2 1381
轻奢々
轻奢々 2020-12-14 04:18

I want the epc column to always be earnings/clicks. I am using an AFTER UPDATE trigger to accomplish this. So if I were to add 100 cli

相关标签:
2条回答
  • 2020-12-14 04:44

    You can't update rows in the table in an after update trigger.

    Perhaps you want something like this:

    CREATE TRIGGER `records_integrity` BEFORE UPDATE
    ON `records`
    FOR EACH ROW
        SET NEW.epc=IFNULL(new.earnings/new.clicks, 0);
    

    EDIT:

    Inside a trigger, you have have access to OLD and NEW. OLD are the old values in the record and NEW are the new values. In a before trigger, the NEW values are what get written to the table, so you can modify them. In an after trigger, the NEW values have already been written, so they cannot be modified. I think the MySQL documentation explains this pretty well.

    0 讨论(0)
  • 2020-12-14 05:02

    Perhaps you could write two separate statements in that transaction

     update record set clicks=...
    
     update record set epc=...
    

    or you could put them inside a function, say updateClick() and just call that function. By doing it this way you can easily alter your logic should the need arise.

    Putting the logic inside a trigger might create a situation where debugging and tracing are made unnecessarily complex.

    0 讨论(0)
提交回复
热议问题