合并 MySQL 更新语句?

mysqlmysqli database更新于 2025/9/15 9:16:17

您可以使用 CASE 语句来实现这一点。让我们首先创建一个表 −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20)
   );
Query OK, 0 rows affected (1.11 sec)

使用 insert 命令在表中插入记录 −

mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.13 sec)

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

mysql> select * from DemoTable;

这将产生以下输出 −

+----+-------+
| Id | Name  |
+----+-------+
| 1  | John  |
| 2  | Carol |
| 3  | David |
+----+-------+
3 rows in set (0.00 sec)

以下是组合 MySQL 更新语句的查询 −

mysql> UPDATE DemoTable set Name= case when Name= 'John' then 'John Smith'
when Name= 'Carol' then 'Carol Taylor'
when Name= 'David' then 'David Miller'
end
where Name IN('John','Carol','David');
Query OK, 3 rows affected (0.12 sec)
Rows matched: 3 Changed: 3 Warnings: 0

让我们显示表中更新的记录 −

mysql> select * from DemoTable;

这将产生以下输出 −

+----+--------------+
| Id | Name         |
+----+--------------+
| 1  | John Smith   |
| 2  | Carol Taylor |
| 3  | David Miller |
+----+--------------+
3 rows in set (0.00 sec)

相关文章


有用资源