Skip to content

Instantly share code, notes, and snippets.

@geekbrit
Created August 9, 2016 15:54
Show Gist options
  • Save geekbrit/49c9b9a5bb2a2084b9514459e847216d to your computer and use it in GitHub Desktop.
Save geekbrit/49c9b9a5bb2a2084b9514459e847216d to your computer and use it in GitHub Desktop.
MySQL Remove duplicate addresses, fix up tables that reference the missing duplicates
create temporary table good_address (
`idAddress` int(11) NOT NULL,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`company_name` varchar(45) NOT NULL,
`address_1` varchar(50) NOT NULL,
`address_2` varchar(50) DEFAULT NULL,
`city` varchar(45) NOT NULL,
`state` varchar(45) DEFAULT NULL,
`country` varchar(5) NOT NULL,
`zip` varchar(12) DEFAULT NULL,
`email` varchar(50) NOT NULL,
`tel` varchar(20) DEFAULT NULL,
`fax` varchar(20) DEFAULT NULL
);
insert into good_address( idAddress, first_name, last_name, company_name, address_1, address_2, city, state, country, zip, email, tel, fax )
select MIN(idAddress), first_name, last_name, company_name, address_1, address_2, city, state, country, zip, email, tel, fax from Address
group by first_name, last_name, company_name, address_1, address_2, city, state, country, zip, email, tel, fax;
update CPO c
left join Address a on a.idAddress = c.billing_address
left join good_address g on
g.first_name = a.first_name and
g.last_name = a.last_name and
g.company_name = a.company_name and
g.address_1 = a.address_1 and
g.address_2 = a.address_2 and
g.city = a.city and
g.state = a.state and
g.country = a.country and
g.zip = a.zip and
g.email = a.email and
g.tel = a.tel
set c.billing_address = g.idAddress;
update CPO c
left join Address a on a.idAddress = c.shipping_address
left join good_address g on
g.first_name = a.first_name and
g.last_name = a.last_name and
g.company_name = a.company_name and
g.address_1 = a.address_1 and
g.address_2 = a.address_2 and
g.city = a.city and
g.state = a.state and
g.country = a.country and
g.zip = a.zip and
g.email = a.email and
g.tel = a.tel
set c.shipping_address = g.idAddress;
delete from Address where idAddress not in (select idAddress from good_address);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment