简体   繁体   English

在MYSQL中添加日期并检查NULL值

[英]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. 检查last_service记录,并将基于天的delivery_frequency记录添加到mysql中的next_service date字段。
  2. However, if last_service is NULL or Empty then update last_service to today's date and do the step 1 afterwards. 但是,如果last_serviceNULLEmpty然后更新last_service今天的日期,但步骤1之后。

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. 我正在用PHP消费这些,但是我不想用PHP做双重查询或其他方式来处理这部分。

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 返回2011-12-31

and

coalesce(null, CURRENT_DATE)

returns 2012-02-06 which is CURRENT_DATE 返回2012-02-06 ,即CURRENT_DATE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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