Skip to content

Instantly share code, notes, and snippets.

@barinek
Created February 6, 2010 20:43
Show Gist options
  • Save barinek/296947 to your computer and use it in GitHub Desktop.
Save barinek/296947 to your computer and use it in GitHub Desktop.
create trigger activity_duplicate_check before insert on activities
for each row begin
set @activity_id=new.activity_id;
set @poll_result_id=new.poll_result_id;
set @created_at=new.created_at;
set @data_collector_id=new.data_collector_id;
begin
declare found_ids int default 0;
declare found_created_at datetime default 0;
declare j int default 0;
while j < 5 and (found_created_at = '0000-00-00 00:00:00' or found_created_at is null)
do
select count(1), created_at into found_ids, found_created_at
from activities use index(index_activities_on_data_collector_id_and_activity_id)
where activity_id = @activity_id
and data_collector_id = @data_collector_id
and created_at > date_sub( date_format(@created_at, '%Y/%m/%d 00:00:00'), interval j day)
and created_at < date_sub( date_format(@created_at, '%Y/%m/%d 23:59:59'), interval j day);
set j = j + 1;
end while;
if found_ids = 0 then
update poll_results set updated_at = @created_at,
poll_results.new_item_count = poll_results.new_item_count + 1
where poll_results.id = @poll_result_id
and data_collector_id = @data_collector_id;
else
set new.created_at=found_created_at;
end if;
end;
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment