MySQL Triggers for On Insert and Update Events
When working with multiple tables, such as the example provided, triggers can be employed to maintain data consistency. In this case, the goal is to update the ext_words_count table based on changes to the ext_words table.
To achieve this, a single trigger can be crafted to handle both insert and update events using conditional statements.
Trigger Code:
DELIMITER $$ CREATE TRIGGER update_count AFTER INSERT ON ext_words FOR EACH ROW BEGIN IF NOT EXISTS (SELECT 1 FROM ext_words_count WHERE word = NEW.word) THEN INSERT INTO ext_words_count (word) VALUES (NEW.word); ELSE UPDATE ext_words_count SET word_count = word_count + 1 WHERE word = NEW.word; END IF; END $$ DELIMITER ;
How the Trigger Works:
Notes:
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!