使用IF条件的MySQL更新

MySQL UPDATE using IF condition

在MySQL中使用IF条件执行UPDATE的语法如下-

1
update yourTableName set yourColumnName =if(yourColumnName =yourOldValue,yourNewValue,yourColumnName);

为了理解上述语法,让我们创建一个表。 创建表的查询如下-

1
2
3
4
5
6
7
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命令在表中插入一些记录。 查询如下-

1
2
3
4
5
6
7
8
9
10
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语句显示表中的所有记录。 查询如下-

1
mysql> select *from updateIfConditionDemo;

这是输出-

1
2
3
4
5
6
7
8
9
10
+--------+----------+---------+
| 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条件进行更新的查询-

1
2
3
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-

1
mysql> select *from updateIfConditionDemo;

这是输出-

1
2
3
4
5
6
7
8
9
10
+--------+----------+---------+
| 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)