如果为NULL,则设置列值(MySQL)

时间:2015-08-06 09:17:29

标签: mysql sql

我正在尝试修改此查询以设置'reason'列的值,如果它为空,则将值设置为'CUSTOM'(下面示例中的第三列)

SELECT
    `t`.`myuser_id` AS `t0_c1`,
    IF (positive.reason IS NOT NULL,
        positive.reason,
        deduction.reason
    ) AS reason,
    `positive`.`achievement_id` AS `t1_c0`,
    `positive`.`reason` AS `t1_c2`,
    `deduction`.`reason` AS `t2_c2`
FROM
    `o_codes` `t`
    LEFT OUTER JOIN `achievements` `positive` ON (`positive`.`achievement_id` = `t`.`order_product_id`)
    LEFT OUTER JOIN `deductions` `deduction` ON (`deduction`.`deduction_id` = `t`.`order_product_id`)
WHERE
    t.myuser_id = 12345;

我的输出示例......

t0_c1 | t0_c2  |   reason   | t1_c0 
1234  | 11481  | Good Stuff | (NULL)
1477  | 11482  |   (NULL)   | (NULL)

如何更改此查询,以便将原因列的值为NULL的第二行设置为“CUSTOM”,同时考虑当前的IF语句仍然需要 - 任何想法?

2 个答案:

答案 0 :(得分:1)

使用IFNULL

IFNULL(expr1, 0)

<强>参考

  

如果expr1不是NULLIFNULL()将返回expr1;否则返回expr2。 &#39; 0&#39;在这种情况下。   IFNULL()返回一个数字或字符串值,具体取决于使用它的上下文。

IFNULL(`positive`.`achievement_id`, 0) AS `t1_c0`,

答案 1 :(得分:0)

IF部分应为

COALESCE(
IF (
positive.reason IS NOT NULL,
positive.reason,
deduction.reason
),'CUSTOM')
 AS reason,