In PHP, I need to change this data
FirstName | MiddleName | LastName
---------------------------------
Robert | Thomas | Smith
Into the string "Smith, Robert Thomas"
I'm not sure if I need to use a join
, concat
or concat_ws
.
I know that if I use
concat_ws(', ',LastName,FirstName,MiddleName)
Then I get "Smith, Robert, Thomas" but i need "Smith, Robert Thomas".
Any advice?
Both CONCAT() and CONCAT_WS() functions are used to concatenate two or more strings but the basic difference between them is that CONCAT_WS() function can do the concatenation along with a separator between strings, whereas in CONCAT() function there is no concept of the separator.
CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.
The CONCAT_WS() function adds two or more expressions together with a separator.
There is no functional difference. || is the ANSI standard string concatenation operator (though, unfortunately, not every database <cough>SQL Server</cough> chooses to support the standard). Many databases support a CONCAT function so it may be easier to port code using CONCAT to different databases.
I realise this is a necro but it is worth noting the following:
Both CONCAT
& CONCAT_WS
are largely equivalent.
However, the most noteworthy difference is that CONCAT
might not return the results you are expecting for cases where any of the inputs are NULL. In these cases CONCAT
will return NULL whereas CONCAT_WS
will skip NULL values and still return a string with the result of the remaining inputs. This means that in most cases you will probably want to use CONCAT_WS
.
The following are equivalent except where one or more inputs are NULL:
// Result: LastName, FirstName, MiddleName
CONCAT( LastName, ', ', FirstName, ', ', MiddleName )
// Result: LastName, FirstName, MiddleName
CONCAT_WS( ', ', LastName, FirstName, MiddleName )
In cases where you want to use CONCAT_WS
with different 'separators' just set the first input to an empty string:
// Result: LastName, FirstName (MiddleName)
CONCAT_WS( '', LastName, ', ', FirstName, ' (', MiddleName, ')' )
Then just use
CONCAT(LastName, ', ', FirstnName, ' ', MiddleName)
CONCAT_WS is used to concatenate with only one seperator while the CONCAT appends strings together in any way you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With