1

I've been trying to figure out a query which will do the followings:

  1. Check last_service record and add delivery_frequency record which is day-based to next_service date field in mysql.
  2. However, if last_service is NULL or Empty then update last_service to today's date and do the step 1 afterwards.

I know how to do the step one which is the following query:

UPDATE events SET next_service = DATE_ADD(last_service,INTERVAL 14 DAY) WHERE order_product_id = 3;

But somewhat I found Step 2nd trickier. Could some one show me how to do that?

I am consuming these with PHP but I don't want to handle this part with PHP doing double query or something.

You can think what I am looking for as following:

UPDATE events SET next_service = IF last_service IS NOT NULL OR '' THEN
DATE_ADD(last_service,INTERVAL 14 DAY) ELSE SET last_service = CURRENT_DATE AND
DATE_ADD(last_service,INTERVAL 14 DAY) END IF WHERE order_product_id = 3;

1 Answer 1

4
UPDATE events
SET
   last_service = coalesce(last_service, CURRENT_DATE),
   next_service = DATE_ADD(coalesce(last_service, CURRENT_DATE), INTERVAL 14 DAY)
WHERE order_product_id = 3;

Coalesce returns the first non-null value, so that

coalesce('2011-12-31', CURRENT_DATE)

returns 2011-12-31

and

coalesce(null, CURRENT_DATE)

returns 2012-02-06 which is CURRENT_DATE

Sign up to request clarification or add additional context in comments.

1 Comment

OK, seriously this is awesome how you came up with this answer. Looks like exactly what I've been looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.