在刷LeetCode的时候遇到的SQL题目
627.Swap Salary
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 |
大概就是要求交换表中sex列的性别
一开始想着用update salary set sex = f when sex = m再用个AND,后来一想这样执行的结果应该是错的、
然后就偷看了solution,才知道还有when case语句,所以记录一下
update salary set sex =
case sex
when 'm' then 'f'
else 'm'
end;
大概意思就是when m,then就设置为f,else都设置为m
最新评论
5211314
能不能教我 一点不会