SQL--leetcode626. 換座位

小美是一所中學的信息科技老師,她有一張 seat 座位表,平時用來儲存學生名字和與他們相對應的座位 id。

其中縱列的 id 是連續遞增的

小美想改變相鄰倆學生的座位。

你能不能幫她寫一個 SQL query 來輸出小美想要的結果呢?

 

示例:

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

假如數據輸入的是上表,則輸出結果如下:

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

注意:

如果學生人數是奇數,則不需要改變最後一個同學的座位。


用union,直接考慮三種情況:

# Write your MySQL query statement below
select p.id,p.student from(
select id+1 as id,student from seat where id%2=1 and id!=(select count(*) from seat)
union select id-1 as id,student from seat where id%2=0
union select id,student from seat where id%2=1 and id=(select count(*)from seat)
)p order by id

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章