如何编写mysql触发器

时间:2013-06-17 10:18:51

标签: mysql sql triggers


有两个表格 表A

如果用户使用此查询“插入A值(abc,1,50);”

然后触发器应该检查“表B”中的student_name,如果student_name已经存在于“表B”中那么 更新表B中的“all_marks”字段,例如,“all_marks”应为60

如果student_name“abc”不在“表B”中,那么同样的student_name,student_class,student_marks应插入表B

delimiter $$
create trigger insert_into_summary 
    after insert on A 
    for each row 
begin
     if
//** here i want to write the if condition **  
     insert into B (name,class,overall_marks)
     values(new.name,new.class,new.marks,);
     else 
     update B set all_marks=old.all_marks+new.student_marks;
end $$
delimiter ;

请帮我解释如何编写触发器。

2 个答案:

答案 0 :(得分:1)

尝试这样......

if (Select Count(Name) from B where B.Name=new.name)<1 
insert into summary_score (name,number,all_marks)
values(new.name,new.marks,new.score);
else 
update B set all_marks=old.all_marks+new.student_marks where B.Name=new.Name;

答案 1 :(得分:1)

您可以使用On Duplicate Key Update来完成此操作。在学生姓名/ ID上添加一个唯一键,然后在触发器中使用以下代码

begin
   insert into summary_score (name,number,all_marks)
   values(new.name,new.marks,new.score)
   on duplicate key update all_marks=old.all_marks+new.student_marks
  where B.Name=new.Name;
end $$