MySQL CONCAT returns NULL if any field contain NULL

后端 未结 6 899
青春惊慌失措
青春惊慌失措 2020-11-28 04:38

I have following data in my table \"devices\"

affiliate_name  affiliate_location  model     ip             os_type    os_version 

cs1             inter             


        
相关标签:
6条回答
  • 2020-11-28 05:03

    CONCAT_WS still produces null for me if the first field is Null. I solved this by adding a zero length string at the beginning as in

    CONCAT_WS("",`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`)
    

    however

    CONCAT("",`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`) 
    

    produces Null when the first field is Null.

    0 讨论(0)
  • 2020-11-28 05:03

    you can use if statement like below

    select CONCAT(if(affiliate_name is null ,'',affiliate_name),'- ',if(model is null ,'',affiliate_name)) as model from devices
    
    0 讨论(0)
  • 2020-11-28 05:06

    convert the NULL values with empty string by wrapping it in COALESCE

    SELECT CONCAT(COALESCE(`affiliate_name`,''),'-',COALESCE(`model`,''),'-',COALESCE(`ip`,''),'-',COALESCE(`os_type`,''),'-',COALESCE(`os_version`,'')) AS device_name
    FROM devices
    
    0 讨论(0)
  • 2020-11-28 05:06
    SELECT CONCAT(isnull(`affiliate_name`,''),'-',isnull(`model`,''),'-',isnull(`ip`,''),'-',isnull(`os_type`,''),'-',isnull(`os_version`,'')) AS device_name
    FROM devices
    
    0 讨论(0)
  • 2020-11-28 05:10

    To have the same flexibility in CONCAT_WS as in CONCAT (if you don't want the same separator between every member for instance) use the following:

    SELECT CONCAT_WS("",affiliate_name,':',model,'-',ip,... etc)
    
    0 讨论(0)
  • 2020-11-28 05:20

    Use CONCAT_WS instead:

    CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.

    SELECT CONCAT_WS('-',`affiliate_name`,`model`,`ip`,`os_type`,`os_version`) AS device_name FROM devices
    
    0 讨论(0)
提交回复
热议问题