MySQL 如何使用单个查询批量更新数据
可以使用CASE命令使用单个查询批量更新MySQL数据。其语法如下 -
update yourTableName
set yourUpdateColumnName = ( Case yourConditionColumnName WHEN Value1 THEN ‘’UpdatedValue’
WHEN Value2 THEN ‘UpdatedValue’
.
.
N
END)
where yourConditionColumnName IN(Value1,Value2,.....N);
为了理解以上概念,让我们创建一个表。创建表的查询如下 -
mysql> create table UpdateAllDemo
−> (
−> BookId int,
−> BookName varchar(200)
−> );
Query OK, 0 rows affected (1.18 sec)
使用insert命令在表中插入一些记录。插入记录的查询如下 -
mysql> insert into UpdateAllDemo values(1000,'Introduction to C');
Query OK, 1 row affected (0.15 sec)
mysql> insert into UpdateAllDemo values(1001,'Introduction to Java');
Query OK, 1 row affected (0.21 sec)
使用select语句从表中显示所有记录。查询如下 -
mysql> select *from UpdateAllDemo;
以下是输出 -
+--------+----------------------+
| BookId | BookName |
+--------+----------------------+
| 1000 | Introduction to C |
| 1001 | Introduction to Java |
+--------+----------------------+
2 rows in set (0.00 sec)
现在,我们将进行批量更新,即将Value ‘Introduction to C’的值更新为‘C in Depth’,将Value ‘Introduction to Java’的值更新为‘Java in Depth’。
- 使用上面显示的CASE命令可实现此目的。查询如下 -
mysql> update UpdateAllDemo
−> set BookName = (CASE BookId WHEN 1000 THEN 'C in Depth'
−> when 1001 THEN 'Java in Depth'
−> END)
−> Where BookId IN(1000,1001);
Query OK, 2 rows affected (0.24 sec)
现在,可以使用select语句检查值是否已更新到表中。
检查表中更新值的查询如下 -
mysql> select *from UpdateAllDemo;
以下是显示批量更新成功的输出 -
+--------+---------------+
| BookId | BookName |
+--------+---------------+
| 1000 | C in Depth |
| 1001 | Java in Depth |
+--------+---------------+
2 rows in set (0.00 sec)
阅读更多:MySQL 教程