我们可以用 if 条件更新 MySQL 吗?


你可以用 IF 条件和 CASE 语句更新 MySQL。为此,我们先创建一个表。创建表的查询 −

mysql> create table UpdateWithIfCondition
   −> (
   −> BookId int,
   −> BookName varchar(200)
   −> );
Query OK, 0 rows affected (0.60 sec)

现在,你可以使用 insert 命令在表中插入记录。查询如下 −

mysql> insert into UpdateWithIfCondition values(1000,'C in Depth');
Query OK, 1 row affected (0.12 sec)

mysql> insert into UpdateWithIfCondition values(1001,'Introduction to Java');
Query OK, 1 row affected (0.14 sec)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from UpdateWithIfCondition;

以下是输出 −

+--------+----------------------+
| BookId | BookName             |
+--------+----------------------+
| 1000   | C in Depth           |
| 1001   | Introduction to Java |
+--------+----------------------+
2 rows in set (0.00 sec)

让我们使用 if 条件将 ‘C in Depth’ 的值更新为 'Introduction to C',并将 1001 的值更新为 2000。查询如下 −

mysql> update UpdateWithIfCondition
   −> set BookName = if(BookName = 'C in Depth','Introduction to C',BookName),
   −> BookId = if(BookId = 1001,2000,BookId);
Query OK, 2 rows affected (0.43 sec)
Rows matched: 2 Changed: 2 Warnings: 0

以上,我们已更新了两个列值。以下是对两个值是否已更新进行检查的查询 −

mysql> select *from UpdateWithIfCondition;

以下是使用 if 成功更新值后显示的输出 −

+--------+----------------------+
| BookId | BookName             |
+--------+----------------------+
| 1000   | Introduction to C    |
| 2000   | Introduction to Java |
+--------+----------------------+
2 rows in set (0.00 sec)

更新于: 30-Jul-2019

540 次浏览

开启您的 职业生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.