要替换表中的值,请使用 CASE 语句。为了理解这个概念,让我们创建一个表。创建表的查询如下
mysql> create table replaceValueDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(10), -> isGreaterThan18 varchar(10) -> );
使用插入命令在表中插入一些记录。
查询如下
mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('John','YES'); mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Carol','NO'); mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Mike','YES'); mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Bob','YES'); mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Larry','NO'); mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('David','NO'); mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('James','DONOTKNOW'); mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Robert','DONOTKNOW');
使用 select 语句显示表中的所有记录。
查询如下
mysql> select *from replaceValueDemo;
以下是输出
+----+--------+-----------------+ | Id | Name | isGreaterThan18 | +----+--------+-----------------+ | 1 | John | YES | | 2 | Carol | NO | | 3 | Mike | YES | | 4 | Bob | YES | | 5 | Larry | NO | | 6 | David | NO | | 7 | James | DONOTKNOW | | 8 | Robert | DONOTKNOW | +----+--------+-----------------+ 8 rows in set (0.00 sec)
这是替换 MySQL 表中值的查询
mysql> update replaceValueDemo set isGreaterThan18=case when isGreaterThan18='YES' THEN 'NO' ELSE 'YES' END -> where isGreaterThan18 IN('YES','NO'); Rows matched: 6 Changed: 6 Warnings: 0
让我们再次检查表记录。
查询如下
mysql> select *from replaceValueDemo;
以下是替换值的输出
+----+--------+-----------------+ | Id | Name | isGreaterThan18 | +----+--------+-----------------+ | 1 | John | NO | | 2 | Carol | YES | | 3 | Mike | NO | | 4 | Bob | NO | | 5 | Larry | YES | | 6 | David | YES | | 7 | James | DONOTKNOW | | 8 | Robert | DONOTKNOW | +----+--------+-----------------+ 8 rows in set (0.00 sec)