hank williams
hank williams

Reputation: 133

How can I update where a given select condition returns a true value?

I want to perform an SQL update

UPDATE  incCustomer SET etaxCode = 'HST' WHERE 

only on records where this is true.

select  etaxCode
from  incCustomer
left join incAddress on incCustomer.iAddressId = incAddress.iId
left join incProvince on incAddress.iProvinceStateId = incProvince.iId
where incAddress.iProvinceStateId in (     2  ,     3   ,      4   ,    6   ,   9 )

I don't think that this is possible with ANSI SQL, but can it be done in MySQL?

Upvotes: 3

Views: 735

Answers (1)

OMG Ponies
OMG Ponies

Reputation: 332631

MySQL UPDATE syntax supports joins in both ANSI-89 and ANSI-92 syntax.

Use:

   UPDATE INCCUSTOMER c
LEFT JOIN INCADDRESS a ON a.iid = c.iaddressid
LEFT JOIN INCPROVINCE p ON p.iid = a.iprovincestateid
      SET c.etaxcode = 'HST'
    WHERE a.iProvinceStateId IN (2,3,4,6,9)

I don't see the point of LEFT JOINing to the province table - I think your UPDATE could be written as:

   UPDATE INCCUSTOMER 
      SET c.etaxcode = 'HST'
    WHERE EXISTS(SELECT NULL
                   FROM INCADDRESS a
                  WHERE a.iid = INCCUSTOMER.iaddressid
                    AND a.iProvinceStateId IN (2,3,4,6,9))

Upvotes: 4

Related Questions