MySQL触发器更新另一个表中的值

时间:2010-07-31 03:17:12

标签: sql mysql triggers

更新/插入表x时我想要的是,将表y中的值递增1

下面的示例,使用select语句,我无法从表格中选择我尝试更新

DELIMITER $$
create trigger occupancy
after insert on tbl_attendence
for each row
begin
    set @course_id = new.course_id;
    set @attendence_date = new.attendence_date;

    if new.reason = 1 then

        update tbl_course_occupancy
        set occupancy_number= (select occupancy_number 
                                from tbl_course_occupancy 
                               where course_id = @course_id 
                                 and occupancy_year = EXTRACT(year from @attendence_date) ) + 1
        where course_id = @course_id 
          and occupancy_year = Extract(year from @attendence_date);

    end if;

end$$

任何帮助都是指定的,谢谢

1 个答案:

答案 0 :(得分:4)

使用:

UPDATE tbl_course_occupancy
   SET occupancy_number = occupancy_number + 1
 WHERE course_id = @course_id 
   AND occupancy_year = Extract(year from @attendence_date);