如何在 MySQL 表中替换带条件的行?
要设置条件并替换行,请使用 MySQL CASE 语句。我们先创建一个表 -
mysql> create table DemoTable1481 -> ( -> PlayerScore int -> ); Query OK, 0 rows affected (0.42 sec)
使用 insert 命令将一些记录插入表 -
mysql> insert into DemoTable1481 values(454); Query OK, 1 row affected (0.41 sec) mysql> insert into DemoTable1481 values(765); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1481 values(890); Query OK, 1 row affected (0.09 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1481;
这将产生以下输出 -
+-------------+ | PlayerScore | +-------------+ | 454 | | 765 | | 890 | +-------------+ 3 rows in set (0.00 sec)
以下是替换 MySQL 表中行的查询 -
mysql> update DemoTable1481 -> set PlayerScore= case when PlayerScore=454 then 1256 -> when PlayerScore=765 then 1865 -> when PlayerScore=890 then 3990 -> end -> ; Query OK, 3 rows affected (0.17 sec) Rows matched: 3 Changed: 3 Warnings: 0
让我们再次检查表记录 -
mysql> select * from DemoTable1481;
这将产生以下输出 -
+-------------+ | PlayerScore | +-------------+ | 1256 | | 1865 | | 3990 | +-------------+ 3 rows in set (0.00 sec)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP