Mysql – Using count in triggers to update another table

countMySQLtrigger

Say i have a table called trx_request with the following data

id | confirmed(TIME) | finished(TIME)
-------------------------------------
1  | 12:05:00        | NULL
2  | 13:11:00        | NULL

and another table called trx_updates with the following data

request(FK) | role(INT) | added(TIME)
------------------------------------------
1           | 1         | 14:02:00

I'd like to make a trigger that after a record is inserted into trx_updates, counts how many records has the same value in the request field (such as how many '1's there are). And then, does a check to see if the count reaches 4 ('1' shows up 4 times). When it does, it updates the trx_requests.finished to NOW().

How would one make a count statement in triggers? or are triggers the way to go?

Best Answer

This trigger does the job:

create trigger trx_updates_atrig
after insert on trx_updates for each row begin
DECLARE updatecount INT;
  set updatecount = ( select count(*) from trx_updates where request = new.request );
  if updatecount=4
    then
      update trx_request set finished=NOW() where id = new.request;
  end if;
end//

SQLFiddle Demo.