biokiwi
biokiwi

Reputation: 109

MySQL trigger to update value in another table

What i want to is when updating/inserting to table x, increment a value in table y, by 1

example below, using a select statement, which i cant use as im selecting from the table im trying to update

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$$

any help is appeciated, thanks

Upvotes: 2

Views: 4159

Answers (1)

OMG Ponies
OMG Ponies

Reputation: 332731

Use:

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

Upvotes: 4

Related Questions