0

I want to update quite a few values in a table. Said values already exist in another table.

I'm selecting said values using the following query:

SELECT c.last_purchase, 
       so.customer_id,
       so.modified_at
  FROM customer c 
 INNER JOIN sale_order so  ON c.customer_id = so.customer_id 
                          AND c.country = so.country 
 WHERE so.created_at > c.last_purchase

So far so good. But my sql skills aren't too great(hey, I'm being honest here).

The correct values are so.modified_at. I want to update c.last_purchase to match so.modified_at.

Originally I was thinking of using a WHEN THEN combination. Or perhaps some sort of stored procedure.

I could this by using a bash script or any other programming language that knows how to connect to a database. But I'd like, if possible, to do this strictly using MySQL. If not possible I'll have to settle for a bash script(I already wrote one).

Honestly, I have no idea where to start.

Any pointing in the right direction is more than appreciated.

1

As per my understanding, you need to update last_purchase field with modified_at field by joining customer table and sale_order table using the conditions you mentioned in your query.

Then try the following query

UPDATE customer   AS c
  JOIN sale_order AS s 
   SET c.last_purchase = s.modified_at
 WHERE c.customer_id = s.customer_id
   AND c.country = s.country
   AND s.created_at > c.last_purchase;
  • Yes, that's what I wanted. I can't believe it was so obvious and I missed it. Thank you very much. – Andrew Jan 23 at 9:35
  • It is more efficient to move conditions back to the JOIN ON clause instead of using them in the WHERE. Plain JOIN creates the cartesian product of two tables that can be huge. If the resulting table is big enough not to fit into the join buffer then on-disk temporary table will be created that significantly slowdown the proceeding. – Kondybas Jan 23 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.