简体   繁体   中英

Adding Dates and Checking NULL values in MYSQL

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;
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM