Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL combine two columns and add into a new column

Tags:

sql

mysql

I have the following structure with a MySQL table:

+----------------+----------------+----------+ |    zipcode     |      city      |   state  | +----------------+----------------+----------+ |     10954      |     Nanuet     |    NY    | +----------------+----------------+----------+ 

I want to combine the above 3 columns into one column like this:

+---------------------+ |      combined       | +---------------------+ | 10954 - Nanuet, NY  | +---------------------+ 

And I want to add this "combined" column to the end of the table without destroying the original 3 fields.

like image 923
stewart715 Avatar asked Apr 25 '11 01:04

stewart715


People also ask

How do I merge two columns in a new column in SQL?

SELECT *, CONCAT(FIRSTNAME, LASTNAME) AS FIRSTNAME FROM demo_table; Output: Here, we can see that FIRSTNAME and LASTNAME is concatenated but there is no space between them, If you want to add space between the FIRSTNAME and LASTNAME then add space(' ') in CONCAT() function. This method will change the original table.

How do I combine data from multiple columns into one in SQL?

Select the same number of columns for each query. Corresponding columns must be the same general data type. Corresponding columns must all either allow null values or not allow null values. If you want to order the columns, specify a column number because the names of the columns you are merging are probably different.


1 Answers

Create the column:

ALTER TABLE yourtable ADD COLUMN combined VARCHAR(50); 

Update the current values:

UPDATE yourtable SET combined = CONCAT(zipcode, ' - ', city, ', ', state); 

Update all future values automatically:

CREATE TRIGGER insert_trigger BEFORE INSERT ON yourtable FOR EACH ROW SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);  CREATE TRIGGER update_trigger BEFORE UPDATE ON yourtable FOR EACH ROW SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state); 
like image 133
squawknull Avatar answered Oct 12 '22 13:10

squawknull