leetcode练习题-mysql:626. 换座位
小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。 其中纵列的 id 是连续递增的 小美想改变相邻俩学生的座位。 你能不能帮她写一个 SQL query 来输出小美想要的结果呢? 示例: +---------+---------+ | id | student | +---------+---------+ | 1 | Abbot | | 2 | Doris | | 3 | Emerson | | 4 | Green | | 5 | Jeames | +---------+---------+ 假如数据输入的是上表,则输出结果如下: +---------+---------+ | id | student | +---------+---------+ | 1 | Doris | | 2 | Abbot | | 3 | Green | | 4 | Emerson | | 5 | Jeames | +---------+---------+
解题思路,
- 1换到2 2换到1 3换到4 4换到3 5不变,
- 1+1 = 2 2-1=1 3+1=4 4-1=3
- 5后面如果有6 就5+1 = 6 6-1 = 5 如果没有 5=5
先取出偶数的id 这里需要用到取余来判断是否为偶数, 取余可以使用mod函数 或者直接用%取,然后将id-1,就完成了偶数对换前一位。
select id-1 as id ,student from seat where mod(id,2)=0
取出奇数id ,这里需要加一个条件,如果最后一个数为奇数,那么不取,转变成sql就是如下, 最后需要将奇数id+1 就完成了奇数与后一位偶数的对换。
select id+1 as id,student from seat where mod(id,2)=1 and id !=(select count(*) from seat
如果最后一条是偶数,那么这里的任务就完成的差不多了,如果是奇数需要再获取这个奇数,那么要先获取总条数,总条数就是最后一位数, 然后在取余,如果有余1代表这个数为奇数。
select id,student from seat where mod(id,2)=1 and id = (select count(*) from seat
那么剩余的任务就是将结果合并起来 这里如果不知道合并关键字就完犊子了, union为合并关键字,union all也是合并关键字,他们的区别可以看我这一篇播客
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)
最后将id字段进行升序排列,那么就得到了以下结果
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;
