【数据库602】 换座位

题目描述:(来源:力扣数据库602)

小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。
其中纵列的 id 是连续递增的
小美想改变相邻俩学生的座位。
你能不能帮她写一个 SQL query 来输出小美想要的结果呢?

Alt
结果:

Alt

注意:
如果学生人数是奇数,则不需要改变最后一个同学的座位。


我的解法:

select s1.id,s1.student
from (
	#id为偶数的同学
    select id-1 as id,student from seat where id%2=0
    UNION ALL
    #id为奇数的同学,剔除总人数为奇数时最后一名同学
    select id+1 as id,student from seat where id%2!=0 AND id<(select count(id) from seat)
    UNION ALL
    #最后一名且id为奇数的同学
    select id,student from seat where id%2!=0 AND id=(select count(id) from seat)
) s1
ORDER BY s1.id;

思路:
1)交换id,而不是交换student
2)id的奇偶性判断;
3)总人数为奇数时,最后一名同学不动;

收获:

  1. 查询的对象有时需要视情况转换成等价的对象,如果这道题去交换student,就会非常麻烦;
  2. 学会使用子查询;
  3. 奇偶性情况的判断使用;
  4. leetcode中貌似不支持使用用户自定义变量,因为刚开始我使用自定义变量存储表中的记录数,但是在leetcode上运行出错;
  5. union all可以联合查询多个表;

【优化】
在leetcode上看到一个思路和我想同,但是更加简练的题解:

# Write your MySQL query statement below
select if(id % 2 = 0,id-1,if(id=(select count(distinct id) from seat),id,id+1)
) id,student 
from seat 
order by id

作者:lemon-123
链接:https://leetcode-cn.com/problems/exchange-seats/solution/mysqljie-by-lemon-123-2/

使用了if嵌套,在计算表中记录数时还使用了distinct去重。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值