MySQL 使用 IF 条件执行更新
mysqlmysqli database
在 MySQL 中使用 IF 条件执行更新的语法如下 −
update yourTableName set yourColumnName =if(yourColumnName =yourOldValue,yourNewValue,yourColumnName);
为了理解上述语法,让我们创建一个表。创建表的查询如下 −
mysql> create table updateIfConditionDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(20), -> UserAge int -> ); Query OK, 0 rows affected (4 min 0.59 sec)
现在,您可以使用 insert 命令在表中插入一些记录。查询如下 −
mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Larry',23); Query OK, 1 row affected (0.11 sec) mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Mike',21); Query OK, 1 row affected (0.20 sec) mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Sam',23); Query OK, 1 row affected (0.15 sec) mysql> insert into updateIfConditionDemo(UserName,UserAge) values('David',23); Query OK, 1 row affected (0.14 sec) mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Maxwell',23); Query OK, 1 row affected (0.18 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from updateIfConditionDemo;
这是输出 −
+--------+----------+---------+ | UserId | UserName | UserAge | +--------+----------+---------+ | 1 | Larry | 23 | | 2 | Mike | 21 | | 3 | Sam | 23 | | 4 | David | 23 | | 5 | Maxwell | 23 | +--------+----------+---------+ 5 rows in set (0.00 sec)
以下是使用 IF 条件 − 进行更新的查询
mysql> update updateIfConditionDemo set UserAge =if(UserAge =23,26,UserAge); Query OK, 4 rows affected (0.20 sec) Rows matched: 5 Changed: 4 Warnings: 0
让我们再次检查表记录。UserAge 已从 23 更新为 26 −
mysql> select *from updateIfConditionDemo;
这是输出 −
+--------+----------+---------+ | UserId | UserName | UserAge | +--------+----------+---------+ | 1 | Larry | 26 | | 2 | Mike | 21 | | 3 | Sam | 26 | | 4 | David | 26 | | 5 | Maxwell | 26 | +--------+----------+---------+ 5 rows in set (0.00 sec)