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.
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.
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.
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);
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