力扣——換座位(數據庫的題
阿新 • • 發佈:2019-02-04
student code gree 一個 select asc 信息 nio weight
小美是一所中學的信息科技老師,她有一張 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 | +---------+---------+
註意:
如果學生人數是奇數,則不需要改變最後一個同學的座位。
# Write your MySQL query statement below SELECT* FROM( SELECT id-1 AS id,student FROM seat WHERE id%2=0 UNION SELECT id+1 AS id,student FROM seat WHERE id%2=1 AND (id+1) <= (SELECT COUNT(*) FROM seat) UNION SELECT id AS id,student FROM seat WHERE id%2=1 AND (id+1) > (SELECT COUNT(*) FROM seat) ) AS T1 ORDER BY id ASC
力扣——換座位(數據庫的題