为有牺牲多壮志,敢教日月换新天。

[SQL]LeetCode627. 交换工资 | Swap Salary

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10472837.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

SQL架构

1 create table if not exists salary(id int, name varchar(100), sex char(1), salary int)
2 Truncate table salary
3 insert into salary (id, name, sex, salary) values ('1', 'A', 'm', '2500')
4 insert into salary (id, name, sex, salary) values ('2', 'B', 'f', '1500')
5 insert into salary (id, name, sex, salary) values ('3', 'C', 'm', '5500')
6 insert into salary (id, name, sex, salary) values ('4', 'D', 'f', '500')

Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table. 

For example: 

| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | m   | 2500   |
| 2  | B    | f   | 1500   |
| 3  | C    | m   | 5500   |
| 4  | D    | f   | 500    |

After running your query, the above salary table should have the following rows:

| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |

给定一个 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    |

129ms
1 # Write your MySQL query statement below
2 select id, name, if(sex = 'm','f','m') sex,salary from salary; 

281ms

1 UPDATE salary
2 SET sex = CASE
3 WHEN sex = 'f' THEN 'm'
4 ELSE 'f'
5 END

282ms

1 # Write your MySQL query statement below
2 update salary set sex= if(sex='m','f','m');

283ms

1 # Write your MySQL query statement below
2 UPDATE salary
3 SET
4     sex = CASE sex
5         WHEN 'm' THEN 'f'
6         ELSE 'm'
7     END;

284ms

1 update salary set sex=case sex when 'm' then 'f' else 'm' end;

287ms

1 # Write your MySQL query statement below
2 update salary set sex= CHAR(ASCII('f') + ASCII('m') - ASCII(sex));

 

posted @ 2019-03-04 20:14  为敢技术  阅读(247)  评论(0编辑  收藏  举报