Home > Database > Mysql Tutorial > body text

一个简单MySQL触发器例子_MySQL

WBOY
Release: 2016-06-01 13:32:30
Original
921 people have browsed it

bitsCN.com

一个简单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`;  

 

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template