【问题标题】:MySQL CONCAT: Add a comma/separator only when field is NOT NULLMySQL CONCAT:仅在字段不为空时添加逗号/分隔符
【发布时间】:2014-11-26 18:40:45
【问题描述】:

总而言之,我有一个更新查询,它会将一串数据(例如 SAVE15)附加到现有字段。目前,我预计该字段中已经包含一些信息,因此我的值附加为“,SAVE15”,这是一个逗号和空格分隔符。这暂时有效,但很快我预计只有在字段不为空时才需要插入逗号和空格。如果它为空,我需要它插入“SAVE15”。这是我当前的查询:

UPDATE sales_flat_order sfo
INNER JOIN sales_flat_order_grid sfog
ON sfog.entity_id = sfo.entity_id
SET sfo.coupon_code = concat(IFNULL(sfo.coupon_code, ""),", SAVE15")
WHERE sfog.increment_id = "12345678";

这是我尝试在必要时使用 CONCAT_WS 添加分隔符:

UPDATE sales_flat_order sfo
INNER JOIN sales_flat_order_grid sfog
ON sfog.entity_id = sfo.entity_id
SET sfo.coupon_code = CONCAT_WS(',',IFNULL(sfo.coupon_code, ""),"SAVE15")
WHERE sfog.increment_id = "12345678";

我一开始以为它可以工作,但后来它在一个空字段中插入了“,SAVE15”。我相信第二个查询是正确的方法,但我似乎使用不正确。

【问题讨论】:

    标签: mysql concat concat-ws


    【解决方案1】:

    Concat_WS 的文档告诉我们,它将跳过任何 Null 字段,但不会跳过空字符串。因此,您必须删除对将 Null 值转换为空字符串的 IfNull(sfo.coupon_code, "") 的调用。

    【讨论】:

    • 使用concat_ws(',' , sfo.coupon_code, ,"SAVE15")
    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    相关资源
    最近更新 更多