Generate new string variable by concatenating two integer variables with MySQL

SMM picture SMM · Jan 24, 2012 · Viewed 21k times · Source

I apologize for the silliness of the question but am a complete neophyte with MySQL and am having trouble even reading the documentation for this. I have a table with two columns "homeid" and "indid", which are both integer data fields. I want to concatenate these together in a new variable "uid" with a hyphen. Desired output would look like this:

uid   homeid   indid
10-1  10       1
10-2  10       2
11-1  11       1

I have tried the following code, which does fine through generating the variable "uid" in which the concatenated variables should sit, but doesn't seem to work (though produces no error) beyond that:

ALTER TABLE table_name
add column uid varchar(10) FIRST; /*adds column uid to table "table_name" as first column*/

UPDATE table_name
SET uid=CONCAT('-' , homeid, indid);

Thanks in advance for your help (and patience).

Answer

Michael Berkowski picture Michael Berkowski · Jan 24, 2012

The function you need here is CONCAT_WS() to use a delimiting separator -, or change around the arguments to CONCAT():

UPDATE table_name SET uid = CONCAT_WS('-' , homeid, indid);

OR change around the arguments to CONCAT()

UPDATE table_name SET uid = CONCAT(homeid, '-', indid);