题目描述:(来源:力扣数据库602)
小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。
其中纵列的 id 是连续递增的
小美想改变相邻俩学生的座位。
你能不能帮她写一个 SQL query 来输出小美想要的结果呢?
结果:
注意:
如果学生人数是奇数,则不需要改变最后一个同学的座位。
我的解法:
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)总人数为奇数时,最后一名同学不动;
收获:
- 查询的对象有时需要视情况转换成等价的对象,如果这道题去交换student,就会非常麻烦;
- 学会使用子查询;
- 奇偶性情况的判断使用;
- leetcode中貌似不支持使用用户自定义变量,因为刚开始我使用自定义变量存储表中的记录数,但是在leetcode上运行出错;
- 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
去重。