1

I have a MySQL db. When a field in a table is updated can I write a function or by some other process get a field in another table to be automatically updated?

ie, and this is what I want to do, if table 1 field discount_code and discount code is 123456, then in table 2 can I have times_code_can_be_used (starts at say 20) automatically reduced by 1???

Not done this before and need some guidance.

Thank you.

user718359
  • 505
  • 3
  • 13
  • 24

2 Answers2

3

yes you can do it using mysql trigger

example :-

delimiter |

CREATE TRIGGER testref BEFORE INSERT ON test1
  FOR EACH ROW BEGIN
    INSERT INTO test2 SET a2 = NEW.a1;
    DELETE FROM test3 WHERE a3 = NEW.a1;
    UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
  END;
|

delimiter ;

Note :Support for triggers is included beginning with MySQL 5.0.2

Gowri
  • 16,587
  • 26
  • 100
  • 160
0

you can just use a trigger function. You can set it to run for a particular table if a field is updated or inserted or deleted. Inside that trigger function, you can put any kind of sql you want with whatever logic you need, in your example, just get data from the updated field and use it to update fields in another table.

Dan Bizdadea
  • 1,292
  • 8
  • 15