在 MySQL 中更新单个列中的多行?
mysqlmysqli database更新于 2025/1/29 14:36:17
要更新单个列中的多行,请使用 CASE 语句。让我们首先创建一个表 −
mysql> create table updateMultipleRowsDemo -> ( -> StudentId int, -> StudentMathScore int -> ); Query OK, 0 rows affected (0.63 sec)
下面是使用 insert 命令向表中插入记录的查询 −
mysql> insert into updateMultipleRowsDemo values(10001,67); Query OK, 1 row affected (0.14 sec) mysql> insert into updateMultipleRowsDemo values(10002,69); Query OK, 1 row affected (0.15 sec) mysql> insert into updateMultipleRowsDemo values(10003,89); Query OK, 1 row affected (0.14 sec) mysql> insert into updateMultipleRowsDemo values(10004,99); Query OK, 1 row affected (0.13 sec) mysql> insert into updateMultipleRowsDemo values(10005,92); Query OK, 1 row affected (0.13 sec)
以下是使用 select 语句显示表中的所有记录的查询 −
mysql> select * from updateMultipleRowsDemo;
这将产生以下输出 −
+-----------+------------------+ | StudentId | StudentMathScore | +-----------+------------------+ | 10001 | 67 | | 10002 | 69 | | 10003 | 89 | | 10004 | 99 | | 10005 | 92 | +-----------+------------------+ 5 rows in set (0.00 sec)
这是在 MySQL 中更新单个列中的多行的查询−
mysql> UPDATE updateMultipleRowsDemo -> SET StudentMathScore= CASE StudentId -> WHEN 10001 THEN 45 -> WHEN 10002 THEN 52 -> WHEN 10003 THEN 67 -> END -> WHERE StudentId BETWEEN 10001 AND 10003; Query OK, 3 rows affected (0.19 sec) Rows matched: 3 Changed: 3 Warnings: 0
让我们检查一下该值是否已更新−
mysql> select * from updateMultipleRowsDemo;
这将产生以下输出 −
+-----------+------------------+ | StudentId | StudentMathScore | +-----------+------------------+ | 10001 | 45 | | 10002 | 52 | | 10003 | 67 | | 10004 | 99 | | 10005 | 92 | +-----------+------------------+ 5 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

