Skip to content

Instantly share code, notes, and snippets.

@matthewpoer
Last active December 18, 2015 08:49
Show Gist options
  • Save matthewpoer/5757012 to your computer and use it in GitHub Desktop.
Save matthewpoer/5757012 to your computer and use it in GitHub Desktop.
I wrote a script that created new Opportunities, but I set the timing wrong and it ran every hour instead of once a day. This created a bit of a mess... here's how I cleaned it up.
-- setup temp table
create table `opp_dups` (
`id` varchar(36) NOT NULL,
PRIMARY KEY (`id`)
);
-- copy the dup IDs into the temp table...
insert into opp_dups(id)
select distinct(opp1.id) from opportunities opp1
join opportunities opp2 on opp1.name=opp2.name and opp1.id <> opp2.id
and opp1.date_closed = opp2.date_closed
and opp1.deleted = 0 and opp2.deleted = 0
and length(opp1.id) = 36 and length(opp2.id) = 36;
-- group the dupes
select id,name,date_closed,count(*) as dups from opportunities
where opportunities.deleted = 0
and length(id) = 36
group by name,date_closed
order by name asc;
-- the wrapup, showing dupe groups that actually count > 1
select * from
(
select id,name,date_closed,count(*) as dups from opportunities
where opportunities.deleted = 0
and length(id) = 36
group by name,date_closed
order by name asc
) as sub
where sub.dups > 1;
-- the re-wrapped update sets deleted=2, which means 'save me!'
update opportunities set deleted=2 where id in
(
select * from
(
select id as dups from opportunities
where opportunities.deleted = 0
and length(id) = 36
group by name,date_closed
order by name asc
) as sub
where sub.dups > 1
);
-- the re-wrapped update that actually soft-deletes things...
update opportunities
set deleted=1 where deleted=0 and id in
(
select id from opp_dups
);
-- and re-activate the '2' group
update opportunities set deleted=0 where deleted=2;
-- and see what we have now
select id,name,date_closed from opportunities where deleted = 0 and length(id) = 36;
-- drop that temp table
drop table `opp_dups`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment