简体   繁体   English

仅当值不为空时才可以使用CONCAT_WS添加分隔符

[英]Is it possible to use CONCAT_WS add separator only if value not empty

Let say I have this table 假设我有这张桌子

id  a       b
1   data    1234
2   data    

I want to concat with separator (but) if no data, don't add the separator. 我想用分隔符连接(但是),如果没有数据,请不要添加分隔符。

If I do 如果我做

UPDATE `table` SET `b` = CONCAT_WS(',',`b`,'newData') WHERE `id` = '1'

I get the expected 1234,newData in b 我在b得到了预期的1234,newData

but II do 但是我会

UPDATE `table` SET `b` = CONCAT_WS(',',`b`,'newData') WHERE `id` = '2'

I get ,newData in b (( but I want only newData without the separator )). 我在b得到了newData((但是我只想要newData而没有分隔符))。

IS there a way to do this ? 有没有办法做到这一点 ?

You can try this one Mate: 您可以尝试一位伴侣:

# [A] sample result set for checking
SELECT 
    `a`, `b`,
    IF(
        (`a` IS NOT NULL AND `a` != '')
        AND (`b` IS NOT NULL AND `b` != ''),
        CONCAT_WS(',', `a`, `b`),
        REPLACE(CONCAT_WS(',', `a`, `b`), ',', '')
    ) `result`
FROM `table`
WHERE `id` IN (1, 2);

If the result set in [A] satisfied what you need, you can proceed with the script using [B] 如果[A]的结果集满足您的需求,则可以使用[B]继续执行脚本


The Update query: 更新查询:

# [B] process query for the new values
UPDATE `table`
SET `b` = IF(
    (`a` IS NOT NULL AND `a` != '')
    AND (`b` IS NOT NULL AND `b` != ''),
    CONCAT_WS(',', `a`, `b`),
    REPLACE(CONCAT_WS(',', `a`, `b`), ',', '')
)
WHERE `id` IN (1, 2);

Hope I can help, cheers! 希望我能帮助,加油!

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

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