交换数据

# 626. 换座位(难度:<font color=orange>**中等**</font>) 小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。 其中纵列的 id 是连续递增的 小美想改变相邻俩学生的座位。 你能不能帮她写一个 SQL query 来输出小美想要的结果呢?  ![批注 20200830 185233.png](https://cos.easydoc.net/17082933/files/keh3lr4d.png) 解法: **(1)IF语句** ```sql select if(id%2=0, id-1, if(id=(select count(distinct id) from seat), id, id+1 ) ) as id,student from seat order by id; ``` **(2)自定义+笛卡尔积+case when** 238 ms ```sql select (case #当座位号是奇数且不是最后一个座位号时 when mod(id,2) = 1 and counts != id then id+1 # 当座位号是奇数并且是最后一个座位号时,座位号不变 when mod(id,2) = 1 and counts = id then id # 当座位号是偶数时 else id-1 end) as id, student from seat, (select count(*) as counts from seat) b order by id asc ```