开发者

MySQL combine two columns and add into a new column

开发者 https://www.devze.com 2023-02-28 17:06 出处:网络
I have the following structure with a MySQL table开发者_运维知识库: +----------------+----------------+----------+

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.


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


Are you sure you want to do this? In essence, you're duplicating the data that is in the three original columns. From that point on, you'll need to make sure that the data in the combined field matches the data in the first three columns. This is more overhead for your application, and other processes that update the system will need to understand the relationship.

If you need the data, why not select in when you need it? The SQL for selecting what would be in that field would be:

SELECT CONCAT(zipcode, ' - ', city, ', ', state) FROM Table;

This way, if the data in the fields changes, you don't have to update your combined field.


Add new column to your table and perfrom the query:

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


SELECT CONCAT (zipcode, ' - ', city, ', ', state) AS COMBINED FROM TABLE

0

精彩评论

暂无评论...
验证码 换一张
取 消