Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - How to batch update given the results of a select

Tags:

sql

mysql

I've got a select statement that joins a couple of tables and grabs some information. I'd like to updated all of the records on one of those tables (found in the select) with information contained in the select. The select looks like this:

SELECT  account.id
        document.id
FROM    customer INNER JOIN account ON
            (customer.firstname = account.firstname AND 
            customer.lastname = account.lastname AND
            customer.phone = account.phone)
        INNER JOIN document ON
            customer.id = document.customerid
WHERE   document.accountid IS NULL;

In english, a document can belong to customers and accounts. I'm looking for the account records that match customer records where the document belongs to the customer, but not the account.

Now, I can manually go through the results and run this:

UPDATE  document
SET     accountid = /*account.id*/
WHERE   id = /*document.id*/;

which works as I would like, but there's a decent amount of records that match my query and I'd like to do it in a single statement if I could.

like image 412
Steven Evers Avatar asked Jan 21 '23 23:01

Steven Evers


1 Answers

UPDATE document, account, customer
SET documnet.accountid = account.id
WHERE (customer.firstname = account.firstname AND customer.lastname = account.lastname AND customer.phone = account.phone)
AND customer.id = document.customerid
AND document.accountid IS NULL;

That should do it all in one go

like image 164
Matt S Avatar answered Feb 01 '23 07:02

Matt S