合并两个MySQL字段并用结果更新第三个字段?
以下是在MySQL中结合两个字段的语法-
alter table yourTableName add column yourColumnName dataType; update yourTableName set yourAddedColumnName =concat(yourColumnName1,' ',yourColumnName2);
让我们首先创建一个表-
mysql> create table DemoTable1590 -> ( -> FirstName varchar(20), -> LastName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1590 values('Adam','Smith'); mysql> insert into DemoTable1590 values('John','Doe'); mysql> insert into DemoTable1590 values('David','Miller');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1590;
这将产生以下输出-
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | Adam | Smith | | John | Doe | | David | Miller | +-----------+----------+ 3 rows in set (0.00 sec)
以下是合并两个MySQL字段并在连接后更新第三个字段的查询-
mysql> alter table DemoTable1590 add column FullName varchar(40); Records: 0 Duplicates: 0 Warnings: 0 mysql> update DemoTable1590 set FullName=concat(FirstName,' ',LastName); Rows matched: 3 Changed: 3 Warnings: 0
让我们再次检查表记录-
mysql> select * from DemoTable1590;
这将产生以下输出-
+-----------+----------+--------------+ | FirstName | LastName | FullName | +-----------+----------+--------------+ | Adam | Smith | Adam Smith | | John | Doe | John Doe | | David | Miller | David Miller | +-----------+----------+--------------+ 3 rows in set (0.00 sec)