背景:seat表(id, student),其中id是递增的,交换相邻位置,如果是奇数个,最后一个不处理
思路:交换id
sql语句如下:
select
(case when mod(id, 2) != 0 and cnt != id then id + 1
when mod(id, 2) != 0 and cnt = id then id
else id - 1
end) as id, student
from seat,
(select count(*) as cnt from seat) tmp
order by id;
另外一种方法
通过左外连接,其中涉及到位操作,奇偶互换(id+1)^1-1
sql语句如下:
select s1.id, coalesce(s2.student, s1.student) as student
from seat s1
left join seat s2
on (s1.id + 1) ^ 1 - 1 = s2.id
order by s1.id;