LeetCode 627. Swap Salary

本文介绍了一种在不使用临时表的情况下,通过单条更新查询实现数据库表中性别字段(male与female)批量互换的方法。利用CASE...WHEN...THEN...ELSE...END语句,巧妙地实现了所有f值变为m,所有m值变为f,适用于各种数据库系统。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

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    |

分析:这道题恰好有我未知的知识,涉及数据库如何有选择地更新,主要是CASE...WHEN...THEN...ELSE...END的使用,可以看我转载的文章,对这个关键字有所介绍。其他就没有更多的了,直接上代码。

解答:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值