小美是一所中學的資訊科技老師,她有一張 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;