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    |

题目链接:


思路分析

将salary表中的性别反转。

使用update更新表格,设置一个case进行判断。

代码

# Write your MySQL query statement below
update Salary set sex = (case when sex = 'm' then 'f' else 'm' end)

时间复杂度:未知
空间复杂度:未知


反思

也可以使用异或。

# Write your MySQL query statement below
update Salary set sex = CHAR(ASCII('f') ^ ASCII('m') ^ ASCII(sex))
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BigFatSheep/article/details/81592456
个人分类: Leetcode Easy
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭