小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。
其中纵列的id是连续递增的
小美想改变相邻俩学生的座位。
你能不能帮她写一个 SQL query 来输出小美想要的结果呢?
Create table If Not Exists seat(id int, studentvarchar(255));
Truncate table seat;
insert into seat (id, student) values ('1','Abbot');
insert into seat (id, student) values ('2','Doris');
insert into seat (id, student) values ('3','Emerson');
insert into seat (id, student) values ('4','Green');
insert into seat (id, student) values ('5','Jeames');
方法一:按题目的要求,对所有数据进行拆分,1、2互换,3、4互换,最后一个是奇数的不动,然后就分成三块来写,第一块就是id为偶数的,id-1就相当于和奇数的互换了,第二块是id为奇数的,id+1就相当于和偶数的互换了,最后一块是最后一个为奇数的,不换,然后三块合并排序就出来结果了
select s.id , s.student from
(
select id-1 as id ,student from seat wheremod(id,2)=0
union
select id+1 as id,student from seat wheremod(id,2)=1 and id !=(select count(*) from seat)
union
select id,student from seat where mod(id,2)=1and id = (select count(*) from seat)
) s order by id;
方法二:此种方法是上面一种方法的一个拓展简化,思路差不多,也有区别
对照上表及其查询结果可以得知,当原id为奇数时,交换座位后的id变为id+1,当原id为偶数时,交换座位后的id变为id-1,另一个方面需要考虑的是,学生人数为奇数时,最后一个学生的id不变,故应当用子查询确定学生的人数,然后分情况讨论即可
select (
case when mod(id,2)!=0 and id!=counts then id+1
when mod(id,2)!=0 and id=counts then id
else id-1 end)as id,student
from seat,(select count(*)as counts from seat)as seat_counts
order by id;
方法三:
select
(
CASE WHEN s.id % 2 = 0 THEN s.id - 1
WHEN s.id % 2 != 0 AND s.id = counts
THEN s.id
ELSE s.id + 1 END
) AS id,
student
from seat s,
(
SELECt count(*) AS counts FROM seat
) AS students_counts
ORDER BY id;