Swap Salary
Description:
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 |
问题描述:
交换所有f和m的值。一条数据如果sex = f -> sex = m,sex = m-> sex = f。
只能有一条更新语句,并且不能使用中间表。
Solution:
问题也可以转化为给定两个变量,不使用中间变量,交换两个变量的值。
update salary set sex = CHAR(ASCII('f') ^ ASCII('m') ^ ASCII(sex));
本来想使用子查询来做的,但是违背了不能使用中间表的要求。即使可以使用中间表,也无法满足只用一条语句达到这个结果,因为不能使用UNION。