在表中用MySQL替换值?
要替换表中的值,请使用 CASE 语句。为了理解该概念,让我们创建一个表。创建表的查询如下
mysql> create table replaceValueDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(10), -> isGreaterThan18 varchar(10) -> ); Query OK, 0 rows affected (0.49 sec)
使用插入命令在表中插入一些记录。
查询如下
mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('John','YES'); Query OK, 1 row affected (0.24 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Carol','NO'); Query OK, 1 row affected (0.16 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Mike','YES'); Query OK, 1 row affected (0.20 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Bob','YES'); Query OK, 1 row affected (0.17 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Larry','NO'); Query OK, 1 row affected (0.09 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('David','NO'); Query OK, 1 row affected (0.11 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('James','DONOTKNOW'); Query OK, 1 row affected (0.14 sec) mysql> insert into replaceValueDemo(Name,isGreaterThan18) values('Robert','DONOTKNOW'); Query OK, 1 row affected (0.13 sec)
使用 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'); Query OK, 6 rows affected (0.19 sec) 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)
广告