如果第二个列不为 NULL,将一列数据更新为 MySQL 中的另一列?
要将一列数据更新到另一列,可以使用 UPDATE 命令。
我们首先创建一个表 -
mysql> create table DemoTable ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserFirstName varchar(20), ListOfName varchar(20) ); Query OK, 0 rows affected (0.59 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable(UserFirstName,ListOfName) values('John','Larry'); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable(UserFirstName,ListOfName) values('Carol',null); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(UserFirstName,ListOfName) values('David','Sam'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable(UserFirstName,ListOfName) values('Bob',null); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable(UserFirstName,ListOfName) values(null,null); Query OK, 1 row affected (0.18 sec)
以下是使用 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; Query OK, 2 rows affected (0.26 sec) 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)
广告