Reputation: 81711
I've been trying to figure out a query which will do the followings:
last_service
record and add delivery_frequency
record which is day-based to next_service
date field in mysql.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;
Upvotes: 1
Views: 156
Reputation: 10248
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
Upvotes: 4