在MySQL中使用IF条件执行UPDATE的语法如下-
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 -> );
现在,您可以使用insert命令在表中插入一些记录。查询如下-
mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Larry',23); mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Mike',21); mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Sam',23); mysql> insert into updateIfConditionDemo(UserName,UserAge) values('David',23); mysql> insert into updateIfConditionDemo(UserName,UserAge) values('Maxwell',23);
使用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); 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)