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

mysqlmysqli database更新于 2024/8/9 19:24:17

您可以使用 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&39;,将 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)


相关文章


有用资源