Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining multiple text fields into one in MySQL

Tags:

sql

mysql

I have a list of users in a table, with separate fields for first, middle, and last name. For various reasons, I need to change the database structure such that there is only one "name" field. What is the best/easiest way to migrate my data from the 3 old fields into my one new field?

like image 713
MrGlass Avatar asked Mar 17 '11 02:03

MrGlass


People also ask

How do I concatenate text from multiple rows into a single text string in MySQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value.

How do I concatenate 3 columns in SQL?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.

How do I concatenate all columns in SQL?

If you have SQL Server 2017 or later, using CONCAT_WS() is the best way to concatenate multiple columns to a string value. Here you have to specify the separator in the form of char, nchar, varchar or nchar as the first argument. Then you can pass on the columns to concatenate in the subsequent arguments.


1 Answers

First add a column that is longer than all 3 combined.

alter table tbl add fullname varchar(100);

Next, update it with the concatenation of the old columns.

update tbl set fullname = concat(lastname, ', ', firstname, ' ', middlename)

(This ends up in the form 'Kirk, John M')

Then, remove the old columns

alter table tbl drop column firstname;
alter table tbl drop column middlename;
alter table tbl drop column lastname;
like image 74
RichardTheKiwi Avatar answered Sep 21 '22 22:09

RichardTheKiwi