LeetCode——627. Swap Salary(数据库,sql)
扫描二维码
随时随地手机看文章
题目链接
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.
| 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 |
题解:
本来想用问号表达式,发现sql中没有,用IF也不会,就参考了下几种解法,不得不说异或确实不错。
UPDATE salary SET sex = IF(sex = 'm', 'f', 'm')
UPDATE salary SET sex = (CASE WHEN sex = 'm' THEN 'f' ELSE 'm' END)
UPDATE salary SET sex = IF(sex = 'm', 'f', 'm')