一個簡單MySQL觸發器例子 有這樣一個需求,更新某張表的某個字段時,要先判斷,如果新值比表中老值小,則將老值和新值相加,然後更新;否則正常更新。考慮用MySQL的觸發器實現,更新時觸發。 下面是具體的sql, 一看便知。 [sql] -- 刪除觸發器 DROP TRIGGER trigger_ads; -- 創建觸發器 DELIMITER // CREATE TRIGGER trigger_ads BEFORE UPDATE ON stats_ads FOR EACH ROW BEGIN IF OLD.VIEW > NEW.VIEW THEN SET NEW.VIEW = OLD.VIEW + NEW.VIEW; END IF; IF OLD.view_unique > NEW.view_unique THEN SET NEW.view_unique = OLD.view_unique + NEW.view_unique; END IF; IF OLD.click > NEW.click THEN SET NEW.click = OLD.click + NEW.click; END IF; IF OLD.click_unique > NEW.click_unique THEN SET NEW.click_unique = OLD.click_unique + NEW.click_unique; END IF; IF OLD.START > NEW.START THEN SET NEW.START = OLD.START + NEW.START; END IF; IF OLD.start_unique > NEW.start_unique THEN SET NEW.start_unique = OLD.start_unique + NEW.start_unique; END IF; IF OLD.landing > NEW.landing THEN SET NEW.landing = OLD.landing + NEW.landing; END IF; IF OLD.landing_unique > NEW.landing_unique THEN SET NEW.landing_unique = OLD.landing_unique + NEW.landing_unique; END IF; END; // 最後可以通過下面sql語句查看所有觸發器: [sql] -- 查看mysql觸發器 SELECT * FROM information_schema.`TRIGGERS`;