如果第二列不为 NULL,在 MySQL 中将一列数据更新为另一列?
mysqlmysqli database
要将一列数据更新为另一列,可以使用 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)
使用 insert 命令在表中插入一些记录 −
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: 00
让我们检查一下 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)