要将一列数据更新为另一列,可以使用UPDATE命令。
让我们首先创建一个表-
mysql> create table DemoTable ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserFirstName varchar(20), ListOfName varchar(20) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(UserFirstName,ListOfName) values('John','Larry'); mysql> insert into DemoTable(UserFirstName,ListOfName) values('Carol',null); mysql> insert into DemoTable(UserFirstName,ListOfName) values('David','Sam'); mysql> insert into DemoTable(UserFirstName,ListOfName) values('Bob',null); mysql> insert into DemoTable(UserFirstName,ListOfName) values(null,null);
以下是使用select语句显示表中所有记录的查询-
mysql> select *from DemoTable;
这将产生以下输出-
+--------+---------------+------------+ | UserId | UserFirstName | ListOfName | +--------+---------------+------------+ | 1 | John | Larry | | 2 | Carol | NULL | | 3 | David | Sam | | 4 | Bob | NULL | | 5 | NULL | NULL | +--------+---------------+------------+ 5 rows in set (0.00 sec)
以下是如果第二列不是NULL则用另一列更新一个列数据的查询-
mysql> update DemoTable set UserFirstName=ListOfName where ListOfName is not null; Rows matched: 2 Changed: 2 Warnings: 0
让我们检查UserFirstName列是否已更新。
mysql> select *from DemoTable;
这将产生以下输出-
+--------+---------------+------------+ | UserId | UserFirstName | ListOfName | +--------+---------------+------------+ | 1 | Larry | Larry | | 2 | Carol | NULL | | 3 | Sam | Sam | | 4 | Bob | NULL | | 5 | NULL | NULL | +--------+---------------+------------+ 5 rows in set (0.00 sec)