使用 MySQL IF 语句更新表中的多个值


我们首先创建一个表 -

mysql> create table DemoTable716 (
   Id varchar(100),
   Value1 int,
   Value2 int,
   Value3 int
);
Query OK, 0 rows affected (0.65 sec)

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

mysql> insert into DemoTable716 values('100',45,86,79);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable716 values('101',67,67,99);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable716 values('102',77,57,98);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable716 values('103',45,67,92);
Query OK, 1 row affected (0.16 sec)

使用 select 语句在表中显示所有记录 -

mysql> select *from DemoTable716;

这将产生以下输出 -

+------+--------+--------+--------+
| Id   | Value1 | Value2 | Value3 |
+------+--------+--------+--------+
| 100  | 45     | 86     | 79     |
| 101  | 67     | 67     | 99     |
| 102  | 77     | 57     | 98     |
| 103  | 45     | 67     | 92     |
+------+--------+--------+--------+
4 rows in set (0.00 sec)

以下是用于更新表中多个值的查询 -

mysql> update DemoTable716
   set Value3=if(Value1=67 OR Value2=67,67,NULL) where Id='101';
Query OK, 1 row affected (0.14 sec)
Rows matched: 1 Changed: 1 Warnings: 0

让我们再次检查表记录 -

mysql> select *from DemoTable716;

这将产生以下输出 -

+------+--------+--------+--------+
| Id   | Value1 | Value2 | Value3 |
+------+--------+--------+--------+
| 100  | 45     | 86     | 79     |
| 101  | 67     | 67     | 67     |
| 102  | 77     | 57     | 98     |
| 103  | 45     | 67     | 92     |
+------+--------+--------+--------+
4 rows in set (0.00 sec)

更新于:2019-08-22

393 次浏览

开启你的职业生涯

完成课程,获得认证

开始
广告