给定一个 salary
表,如下所示,有m=男性 和 f=女性的值 。交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求使用一个更新查询,并且没有中间临时表。
例如:
| id | name | sex | salary | |----|------|-----|--------| | 1 | A | m | 2500 | | 2 | B | f | 1500 | | 3 | C | m | 5500 | | 4 | D | f | 500 |
运行你所编写的查询语句之后,将会得到以下表:
| id | name | sex | salary | |----|------|-----|--------| | 1 | A | f | 2500 | | 2 | B | m | 1500 | | 3 | C | f | 5500 | | 4 | D | m | 500 |
Answer1:
update salary set sex = if(sex='m','f','m');
Answer2:
1. update salary set sex = (case when sex='m' then 'f' else 'm' end);
2. update salary set sex = (case sex when 'm' then 'f' else 'm' end);
那MySQL语句中 if 和case when是如何使用的就很重要了
MySQL的if既可以作为表达式用,也可在存储过程中作为流程控制语句使用,如下是做为表达式使用:
update salary set sex = if(sex='m', 'f', 'm');
如果set='m'(作为条件判断)为真,执行sex='f', 否则执行sex='m'
换成case when就变成:
if(n=1, 'a', 'b') = case n when 1 then 'a' else 'b' end = case when n=1 then 'a' else 'b' end
MySQL的if既可以作为表达式用,也可在存储过程中作为流程控制语句使用,如下是做为流程控制语句使用:
if test1 then
test2
[elseif test3 then]
test4 ...
[else
test5]
end if