为此,请使用CASE语句。让我们首先创建一个表-
mysql> create table DemoTable ( Value char(1) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('a'); mysql> insert into DemoTable values('b'); mysql> insert into DemoTable values('a'); mysql> insert into DemoTable values('a'); mysql> insert into DemoTable values('b'); mysql> insert into DemoTable values('a'); mysql> insert into DemoTable values('b');
使用select语句显示表中的所有记录
mysql> select *from DemoTable;
这将产生以下输出-
+-------+ | Value | +-------+ | a | | b | | a | | a | | b | | a | | b | +-------+ 7 rows in set (0.00 sec)
以下是用'b'更新'a'记录并用'a'更新'b'的查询-
mysql> update DemoTable set Value=case when Value='a' then 'b' else 'a' end; Rows matched: 7 Changed: 7 Warnings: 0
让我们再次检查表记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-------+ | Value | +-------+ | b | | a | | b | | b | | a | | b | | a | +-------+ 7 rows in set (0.00 sec)