如何使用CASE语句更新特定列的值?
为此,请使用UPDATE命令以及CASE语句。让我们先创建一个表 –
mysql>create table DemoTable1925
(
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName varchar(20),
StudentMarks int
);
查询成功,受影响的行数为0(0.00秒)
使用insert命令在表中插入一些记录 –
mysql>insert into DemoTable1925(StudentName,StudentMarks) values('Chris',98);
查询成功,受影响的行数为1(0.00秒)
mysql>insert into DemoTable1925(StudentName,StudentMarks) values('David',45);
查询成功,受影响的行数为1(0.00秒)
使用select语句从表中显示所有记录 –
mysql>select * from DemoTable1925;
这将产生以下输出 –
+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
| 1 | Chris | 98 |
| 2 | David | 45 |
+-----------+-------------+--------------+
共2行(0.00秒)
以下是使用CASE语句提取的特定列值来更新的查询 –
mysql>update DemoTable1925
set StudentMarks=case StudentMarks when 45 then 98
when 98 then 0 end
where StudentMarks IN(45,98);
查询成功,受影响的行数为2(0.00秒)
匹配的行数:2 更改的行数:2 警告:0
让我们再次检查表记录 –
mysql>select * from DemoTable1925;
这将产生以下输出 –
+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
| 1 | Chris | 0 |
| 2 | David | 98 |
+-----------+-------------+--------------+
共2行(0.00秒)
阅读更多:MySQL 教程
极客教程