I am dynamically building a MySQL concatenation with multiple fields and different separators. I’d like to drop the separator if the currently concatenated field is blank or null.
$concat_string = "CONCAT_WS('".$infix_array[0]."'," . $concat_fields_array[0] . "," . $concat_fields_array[1] . ")";
$i = 0;
foreach($concat_fields_array as $concat_field){
if($i >= 2){
$concat_string = "CONCAT_WS('".$infix_array[$i-1]."'," . $concat_string . "," . $concat_field . ")";
}
$i++;
}
This builds a nested CONCAT_WS like:
CONCAT_WS(', ',CONCAT_WS(' - ',CONCAT_WS(':',CONCAT_WS(' ',field1,field2),field3),field4),field5)
Would wrapping the fields in NULLIF like NULLIF(field1, ”) get rid of extra infixes?
Is there a faster function to accomplish this?
You don’t have a problem with NULL fields, because CONCAT_WS will skip NULL values (together with separator). Regarding empty strings (which will not be skipped), you can just turn them into NULLs before doing this. If you cannot update the database itself, then make a query like:
so, just convert it to null on the fly and make your select from that inner query.
In order to make this work, you will have to use nullif, so instead of:
use
I don’t think that you will find a faster way of doing that. Another option might be to just select those fields and then make concatenation on the PHP side, but that is possible only if your resulting concatenation is not part of some WHERE clause further in your query.