MySQL合并两列并添加到新列中 [英] MySQL combine two columns and add into a new column

查看:404
本文介绍了MySQL合并两列并添加到新列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MySQL表具有以下结构:

I have the following structure with a MySQL table:

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

我想将以上3列合并为一列,如下所示:

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

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

我想将此组合"列添加到表的末尾而又不破坏原始的3个字段.

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

推荐答案

创建列:

ALTER TABLE yourtable ADD COLUMN combined VARCHAR(50);

更新当前值:

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

自动更新所有未来值:

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

这篇关于MySQL合并两列并添加到新列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆