626. Exchange Seats-(LeetCode之Database篇)

问题表述


数据库表如下:

id student
1 Abbot
2 Doris
3 Emerson
4 Green
5 Jeames

现在要通过SQL语句将表变换成如下:

id student
1 Doris
2 Abbot
3 Green
4 Emerson
5 Jeames

即id不变,奇数位和偶数位交换位置,如果表的总行数为奇数,则最后一行不变。

问题解决


首先看到这个问题,我就想SQL里面是不是有什么置换函数之类的,结果去查了查,并没有这样的函数。在我尝试了各种select方法后,还是没能将这题解出来…最后还是去讨论区看了看大神们的解答,看完各种答案后瞬间豁然开朗。

这题的解题思路其实并不是想办法将student的列置换,而是通过操作id列来达到置换的效果。

比较通过的解法就是下面这种:

select
if(id < (select count(*) from seat), if(id mod 2=0, id-1, id+1), if(id mod 2=0, id-1, id)) as id, student
from seat
order by id asc

其中IF函数的用法:

格式:IF(Condition,A,B)
意义:当Condition为TRUE时,返回A;当Condition为FALSE时,返回B。

所以上面的SQL语句就是,先对id进行操作。先计算总行数,最后一行如果是奇数id不变,如果是偶数id减1,其余行id为奇数的让id加1,id为偶数的让id减1,最后再对id做升序操作,就可以得到结果了。

其中还有一种解法:

/* get all the even numbered rows as odd numbered rows */
SELECT s1.id - 1 as id, s1.student
FROM Seat s1
WHERE s1.id MOD 2 = 0

UNION

/* get all the odd numbered rows as even numbered rows */
SELECT s2.id + 1 as id, s2.student
FROM Seat s2
WHERE s2.id MOD 2 = 1 AND s2.id != (SELECT MAX(id) FROM Seat)
/* Just don't get the last row as we will handle it in the next UNION */

UNION

/* get the last row if odd and don't change the id value */
SELECT s3.id, s3.student
FROM Seat s3
WHERE s3.id MOD 2 = 1 AND s3.id = (SELECT MAX(id) FROM Seat)

/* Order the result by id */
ORDER BY id ASC;

思路都和第一种方法大同小异。

猜你喜欢

转载自blog.csdn.net/KKSJS/article/details/80579546