Skip to content

Instantly share code, notes, and snippets.

@matthewpoer
Created August 26, 2013 15:03
Show Gist options
  • Save matthewpoer/6342398 to your computer and use it in GitHub Desktop.
Save matthewpoer/6342398 to your computer and use it in GitHub Desktop.
Update Contact records to match the User Assignment (assigned_user_id) of their related Account
-- Find the Contacts whose User Assignments do not match that of parent Accounts
select
contacts.last_name,contacts.assigned_user_id,
accounts.name,accounts.assigned_user_id
from contacts
join accounts_contacts on contacts.id = accounts_contacts.contact_id
join accounts on accounts.id = accounts_contacts.account_id
where contacts.deleted=0 and accounts_contacts.deleted=0 and accounts.deleted=0
and contacts.assigned_user_id <> accounts.assigned_user_id;
-- Same, but just count() them
select count(*) from contacts
join accounts_contacts on contacts.id = accounts_contacts.contact_id
join accounts on accounts.id = accounts_contacts.account_id
where contacts.deleted=0 and accounts_contacts.deleted=0 and accounts.deleted=0
and contacts.assigned_user_id <> accounts.assigned_user_id;
-- Update Contacts to match Assigned User of parent Account
update contacts
join accounts_contacts on accounts_contacts.contact_id = contacts.id
join accounts on accounts.id = accounts_contacts.account_id
set contacts.assigned_user_id
= accounts.assigned_user_id
where contacts.deleted=0 and accounts_contacts.deleted=0 and accounts.deleted=0
and contacts.assigned_user_id <> accounts.assigned_user_id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment