MySQL 触发器使用

来源:互联网 发布:快感增强液 知乎 编辑:程序博客网 时间:2024/06/06 15:35
  1. 什么是触发器???
    简单的来说就是当执行某条sql语句的时候,会触发另外一条sql语句的执行!

  2. 触发器使用场景:
    a. 逻辑不是很复杂的sql
    b. 两个表具有一定的关联性,一个表数据改变,另外一个表数据也会随之变化
    c. 不适合做太复杂的操作! 一般复杂的操作最好是程序员自己写代码去实现,或者使用mysql的存储过程,

  3. 触发器创建

    create trigger [trigger name] [operate type] on [table name] for each row [sql statment]

举个例子:

create trigger test_trigger on user for each row update user_points set total points = 100;

四. 删除触发器

drop trigger trigger_name;

五. 查看已经创建的触发器

show triggers; //显示所有的触发器

六. 实例
比如有这么一个需求: 一个文章表,一个文章的点赞表。 一篇文章可以被多个人点赞,那么我们要知道篇文章的点赞书,最简单的做法就是在文章表中给一个总的点赞数的字段,这样就不用去统计点赞表跟这篇文章相关联的点赞记录。

创建表 article

create table article(    id int not null ,    title varchar(200) not null,    total_good int not null default 0,);

创建点赞表

create table good(    id int not null ,    user_id int null    aid int not null comment '关联的文章表的id',);
insert into article values(1,'hi this is test',0);

创建触发器

create trigger good_ai after insert on good for each row update article set total_good = old.total_good + 1 where good.aid = article.id
0 0
原创粉丝点击