SQL Sub查询Seat Exchange

时间:2018-02-08 19:16:37

标签: mysql sql

我试图理解这个子查询是如何工作的。问题如下

玛丽是一所中学的老师,她有一个座位,可以存放学生的姓名和相应的座位ID。栏目ID是连续增量。 玛丽想改变邻近学生的座位。

 SELECT
(CASE
    WHEN MOD(id, 2) != 0 AND counts != id THEN id + 1
    WHEN MOD(id, 2) != 0 AND counts = id THEN id
    ELSE id - 1
END) AS id,
student
FROM
seat,
(SELECT
    COUNT(*) AS counts
FROM
    seat) AS seat_counts
ORDER BY id ASC;

我试图了解上述查询的工作原理。所以在CASE中它检查id是奇数还是偶数并检查计数以查看它是否是最后一个元素。但ORDER BY ASC如何运作?因为它第一次选择学生Dorris和id 2.但是如何将id 2分配给Abbot。感谢。

SQL表

id   | student 

1    | Abbot   
2    | Doris   
3    | Emerson
4    | Green   
5    | Jeames  

结果将如下所示

id   | student

1    | Dorris
2    | Abbot 
3    | Green 
4    | Emerson
5    | Jeames

3 个答案:

答案 0 :(得分:1)

确定这是做什么的如果 - 如果一个id号是奇数并且它不是最大号,那么加一个,否则从中减去一个。

应该很清楚,除了最后一对之外,它们都会交换。

我认为写得很糟糕我会这样写:

WITH student_count(max) as
(
   SELECT COUNT(*) FROM  seat
)
SELECT
  CASE
    WHEN student_count.max != id AND MOD(id, 2) != 0 THEN id + 1 
    WHEN student_count.max != id AND MOD(id, 2) = 0 THEN id - 1 
    ELSE id
  END AS id,
  student
FROM seat
CROSS JOIN student_count
ORDER BY id ASC;

答案 1 :(得分:0)

我建议您通过删除ORDER BY语句来检查结果。删除ORDER BY语句时,结果将为:

{{1}}

哪种情况完全适合您的情况。基本上,您的查询只是根据CASE语句改变id的值。当您添加ORDER BY id ASC语句时,它只是对上面的结果进行排序。

答案 2 :(得分:0)

select name,
       case when mod(seat_id,2) = 1 and seat_id <> (select max(seat_id) from students) then seat_id + 1 
            when mod(seat_id,2)= 0 then seat_id - 1
            when mod(seat_id,2) = 1 and seat_id = (select max(seat_id) from students) then seat_id
       end swap
from students