如果列为空,请检查其他列

时间:2017-04-14 08:18:41

标签: mysql sql

我在下表中,其中dangling blob f7f7076e53ec9d5a7bde5dcac55af66ea269a5d0 dangling blob f837cd05aa401ba36b1a41a6cc7e7e87c25c0ae3 order_date类型为' varchar'

delivery_date

我需要所有

的记录
id      name        order_date      delivery_date
---------------------------------------------------------
1       A           04/01/2017      04/08/2017
2       B           04/01/2017      NULL
3       C           04/02/2017      04/03/2017
4       D           04/04/2017      04/05/2017
5       E           04/05/2017      04/11/2017
6       F           04/11/2017      NULL
7       G           04/15/2017      04/17/2017
8       H           04/18/2017      NULL

我正在尝试此代码:

* delivery_date between 04/01/2017 TO 04/15/2017
* if delivery_date IS NULL then check order_date between 04/01/2017 TO 04/15/2017
    (in this case order_date is assumed as delivery_date)

但是给出了这个错误:

SELECT *,
IF(delivery_date IS NOT NULL, `delivery_date`, `order_date`) as `final_date`
FROM `test` 
WHERE STR_TO_DATE(`final_date` ,'%m/%d/%Y') BETWEEN STR_TO_DATE('04/01/2017','%m/%d/%Y') AND STR_TO_DATE('04/15/2017','%m/%d/%Y')

3 个答案:

答案 0 :(得分:2)

您正尝试使用WHERE中不允许的列别名。您将不得不使用以下整个表达式

IF(delivery_date IS NOT NULL, `delivery_date`, `order_date`)

您的WHERE子句应该是

WHERE STR_TO_DATE(COALESCE(`delivery_date`, `order_date`) ,'%m/%d/%Y') BETWEEN STR_TO_DATE('04/01/2017','%m/%d/%Y') 
AND STR_TO_DATE('04/15/2017','%m/%d/%Y')

答案 1 :(得分:1)

SELECT *,
IF(delivery_date IS NOT NULL, `delivery_date`, `order_date`) as `final_date`
FROM `test` 
WHERE STR_TO_DATE(IFNULL(`delivery_date`,`final_date`) ,'%m/%d/%Y') BETWEEN STR_TO_DATE('04/01/2017','%m/%d/%Y') AND STR_TO_DATE('04/15/2017','%m/%d/%Y')

尝试上面的代码。希望这会有所帮助。

答案 2 :(得分:0)

我已经在@Rahul和@Sagar Gangwal提供的样本帮助下找到了查询。查询是:

column<a[row].length