Leetcode数据库题解-626. Exchange Seats

题目地址:https://leetcode.com/problems/exchange-seats/

题目:玛丽编写一个查询以改变邻近学生的座位,如果学生人数是奇数,则不需要改变最后一个座位。与其变换名称,不如将id为2n变换为2n-1,2n-1变换为2n (n=1,2,3....)。

第一种:该方法通不过测试,因为是两个sql语句。

update seat t1, seat t2
set t1.student = t2.student, t2.student=t1.student
where t1.id%2=1 and t2.id=t1.id+1;

select * from seat;

第二种:

select s.id,s.student from 
(select id-1 as id,student from seat where mod(id,2)=0
union
 select id+1 as id,student from seat where mod(id,2)=1 and id!=(select count(*) from seat)
 union
 select id,student from seat where mod(id,2)=1 and id=(select count(*) from seat)
) s
order by id

第三种:采用case来实现

select case when id=(select max(id) from seat) and mod(id,2)=1 then id
            when id<(select max(id) from seat) and mod(id,2)=1 then id+1
            when mod(id,2)=0 then id-1
            end as id,
            student
from seat
order by id
            

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值