MySQL 查询用于更新具有相同值的每一个交替行字符串?


我们首先创建一个表 -

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Subject varchar(100)
   -> );
Query OK, 0 rows affected (0.76 sec)

使用 insert 命令在表中插入一些记录 -

mysql> insert into DemoTable(Subject) values('C');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(Subject) values('Java');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Subject) values('Python');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.16 sec)

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

mysql> select *from DemoTable;

输出

+----+---------+
| Id | Subject |
+----+---------+
| 1  | C       |
| 2  | MongoDB |
| 3  | Java    |
| 4  | MongoDB |
| 5  | Python  |
| 6  | MongoDB |
+----+---------+
6 rows in set (0.00 sec)

以下是更新每一秒行字符串的查询 -

mysql> update DemoTable set Subject=replace(Subject,'MongoDB','MySQL') where Id%2=0;
Query OK, 3 rows affected (0.17 sec)
Rows matched: 3 Changed: 3 Warnings: 0

让我们检查表中的所有记录 -

mysql> select *from DemoTable;

输出

+----+---------+
| Id | Subject |
+----+---------+
| 1  | C       |
| 2  | MySQL   |
| 3  | Java    |
| 4  | MySQL   |
| 5  | Python  |
| 6  | MySQL   |
+----+---------+
6 rows in set (0.00 sec)

更新于: 2019-07-30

189 次浏览

开启你的 职业生涯

完成本课程,获得认证

开始学习
广告