将两个 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) -> ); Query OK, 0 rows affected (0.57 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1590 values('Adam','Smith'); Query OK, 1 row affected (0.45 sec) mysql> insert into DemoTable1590 values('John','Doe'); Query OK, 1 row affected (0.42 sec) mysql> insert into DemoTable1590 values('David','Miller'); Query OK, 1 row affected (0.16 sec)
使用 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); Query OK, 0 rows affected (0.54 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> update DemoTable1590 set FullName=concat(FirstName,' ',LastName); Query OK, 3 rows affected (0.56 sec) 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)
广告