MySQL_项目8: 换座位(难度:中等)

项目8: 换座位(难度:中等)

小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。

其中纵列的 id 是连续递增的,小美想改变相邻俩学生的座位,你能不能帮她写一个 SQL query 来输出小美想要的结果呢?

 请创建如下所示seat表:

示例:

+---------+---------+

| id | student |

+---------+---------+

| 1 | Abbot |

| 2 | Doris |

| 3 | Emerson |

| 4 | Green |

| 5 | Jeames |

+---------+---------+

 

假如数据输入的是上表,则输出结果如下:

+---------+---------+

| id | student |

+---------+---------+

| 1 | Doris |

| 2 | Abbot |

| 3 | Green |

| 4 | Emerson |

| 5 | Jeames |

+---------+---------+

注意:如果学生人数是奇数,则不需要改变最后一个同学的座位。

 

-- 创建seat表
CREATE TABLE seat (
id int(11) NOT NULL,
student varchar(20) NOT NULL,
PRIMARY KEY (`id`));

-- 插入数据
INSERT INTO seat VALUES ('1', 'Abbot');
INSERT INTO seat VALUES ('2', 'Doris');
INSERT INTO seat VALUES ('3', 'Emerson');
INSERT INTO seat VALUES ('4', 'Green');
INSERT INTO seat VALUES ('5', 'Jeames');

 

查询SQL代码:

-- id为偶数时,将id-1
SELECT id-1 as id,student
FROM seat
WHERE id % 2=0

UNION

-- id为奇数且最后一个数不是奇数时,将id+1
SELECT id+1 as id,student
FROM seat
WHERE id % 2=1 AND id < (SELECT COUNT(*) from seat)

UNION

-- id为奇数且最后一个数是奇数时,id不变
SELECT *
FROM seat
WHERE id % 2=1 AND id =(SELECT COUNT(*) from seat)

ORDER BY id;

 

转载于:https://www.cnblogs.com/wodexk/p/10707007.html

你可能感兴趣的:(数据库)