【SQL】626. 换座位 (case when... then; 位运算)

64 篇文章 1 订阅
文章介绍了两种在MySQL中实现交换座位的方法。方法一是使用CASE语句,根据ID的奇偶性和计数条件调整ID。方法二是利用位运算和COALESCE函数,通过(a.id+1)^1-1进行ID匹配。这两种方法都是为了在保持排序的前提下交换相邻座位的学生。
摘要由CSDN通过智能技术生成

在这里插入图片描述
在这里插入图片描述

方法一:case

# Write your MySQL query statement below

select 
    (case
        when MOD(id, 2) != 0 and counts != id then id + 1
        when MOD(id, 2) != 0 and counts = id then id
        else id - 1
    end )as id, student
from Seat, (select count(*) as counts from Seat ) as seat_counts
order by id ASC;

方法二:位运算 COALESCE()函数

select a.id, COALESCE(b.student, a.student) as student
from seat a
left join seat b 
on ((a.id + 1) ^ 1) - 1 = b.id
order by a.id;

补充:

a.id -> b.id
位运算:(a.id + 1) ^ 1) - 1
举例子:
1 + 1> 2 ^ 1> 3> 2
2 + 1> 3 ^ 1> 2> 1
3 + 1> 4 ^ 1> 5> 4
4 + 1> 5 ^ 1> 4> 3
5 + 1> 6 ^ 1> 7> 6

参考: https://leetcode.cn/problems/exchange-seats/solutions/50432/huan-zuo-wei-by-leetcode/

仅take notes,如有侵权,请联系删除,感谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值