对于在使用UPDATE Query的同时使用MySQL CASE语句,可以使用CASE语句。让我们首先创建一个表-
mysql> create table DemoTable ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserScore int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(UserScore) values(100); mysql> insert into DemoTable(UserScore) values(110); mysql> insert into DemoTable(UserScore) values(120); mysql> insert into DemoTable(UserScore) values(200); mysql> insert into DemoTable(UserScore) values(230); mysql> insert into DemoTable(UserScore) values(250); mysql> insert into DemoTable(UserScore) values(270);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+--------+-----------+ | UserId | UserScore | +--------+-----------+ | 1 | 100 | | 2 | 110 | | 3 | 120 | | 4 | 200 | | 5 | 230 | | 6 | 250 | | 7 | 270 | +--------+-----------+ 7 rows in set (0.00 sec)
以下是在使用UPDATE查询时使用CASE语句的查询-
mysql> update DemoTable set UserScore = CASE WHEN UserScore BETWEEN 100 AND 120 THEN UserScore + 5 WHEN UserScore BETWEEN 130 AND 230 THEN UserScore +10 WHEN UserScore >=250 THEN UserScore * 5 ELSE UserScore END; Rows matched: 7 Changed: 7 Warnings: 0
现在您可以再次显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+--------+-----------+ | UserId | UserScore | +--------+-----------+ | 1 | 105 | | 2 | 115 | | 3 | 125 | | 4 | 210 | | 5 | 240 | | 6 | 1250 | | 7 | 1350 | +--------+-----------+ 7 rows in set (0.00 sec)