如何使用 MySQL 更新特定列中的所有条目,除单个值外?


若要在忽略单个值的情况下更新所有条目,你需要使用 IF()。

让我们首先创建一张表 -

mysql> create table DemoTable736 (
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(100),
   isMarried boolean
);
Query OK, 0 rows affected (0.53 sec)

使用 insert 命令在表中插入一些记录 -

mysql> insert into DemoTable736(CustomerName,isMarried) values('Chris',0);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Robert',0);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('David',0);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Mike',0);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Carol',1);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Bob',0);
Query OK, 1 row affected (0.20 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable736;

这将产生以下输出 -

+------------+--------------+-----------+
| CustomerId | CustomerName | isMarried |
+------------+--------------+-----------+
| 1          | Chris        | 0         |
| 2          | Robert       | 0         |
| 3          | David        | 0         |
| 4          | Mike         | 0         |
| 5          | Carol        | 1         |
| 6          | Bob          | 0         |
+------------+--------------+-----------+
6 rows in set (0.00 sec)

以下是使用 MySQL 在特定列中更新除单个值以外的所有条目的查询。这里我们更新了 “isMarried” 列 -

mysql> update DemoTable736 set isMarried=if(CustomerId=5,1,1);
Query OK, 5 rows affected (0.13 sec)
Rows matched: 6 Changed: 5 Warnings: 0

让我们再次检查表记录 −

mysql> select *from DemoTable736;

这将产生以下输出 -

+------------+--------------+-----------+
| CustomerId | CustomerName | isMarried |
+------------+--------------+-----------+
| 1          | Chris        | 1         |
| 2          | Robert       | 1         |
| 3          | David        | 1         |
| 4          | Mike         | 1         |
| 5          | Carol        | 1         |
| 6          | Bob          | 1         |
+------------+--------------+-----------+
6 rows in set (0.00 sec)

更新于: 22-Aug-2019

1K+ 浏览

开启您职业生涯

通过完成课程获得认证

开始
广告