在 MySQL 中更新单列中的多行?
要更新单列中的多行,请使用 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)
广告