0

MySQL新手在这里!我有一个由 ID(主键)和学生姓名组成的“座位”表。我的任务是编写一个 SQL 查询来交换每两个连续学生的座位 ID。如果学生人数为奇数,则不交换最后一名学生的 id。id 是连续递增的,结果表应按 id 升序排列。请参阅下面的输入和输出:

输入:

Seat table:
+----+---------+
| id | student |
+----+---------+
| 1  | Abbot   |
| 2  | Doris   |
| 3  | Emerson |
| 4  | Green   |
| 5  | Jeames  |
+----+---------+
Output: 
+----+---------+
| id | student |
+----+---------+
| 1  | Doris   |
| 2  | Abbot   |
| 3  | Green   |
| 4  | Emerson |
| 5  | Jeames  |
+----+---------+

这是我的尝试:

CREATE TABLE Seats ( #skapar employee tabellen
  id INT PRIMARY KEY, 
  student VARCHAR(20)
);

INSERT INTO Seats VALUES(1, 'Abbot');
INSERT INTO Seats VALUES(2, 'Doris');
INSERT INTO Seats VALUES(3, 'Emerson');
INSERT INTO Seats VALUES(4, 'Green');
INSERT INTO Seats VALUES(5, 'Jeams');

现在我做一个程序:

DELIMITER //
CREATE PROCEDURE Test() 
  BEGIN
    DECLARE x INT;
    DECLARE nbrSeats INT;
    SET x = 1;
    SET nbrSeats = COUNT(Seats.id);
    WHILE x < nbrSeats DO
        UPDATE Seats
            SET Seats.id = 0
            WHERE Seats.id = x+1;
        UPDATE Seats
            SET Seats.id = x+1
            WHERE Seats.id = x;
        UPDATE Seats
            SET Seats.id = x
            WHERE Seats.id = 0;
        SET x = x+2;
    END WHILE;
  END //

调用后问题来了:

DELIMITER ;
CALL Test();
SELECT *
FROM Seats
ORDER BY Seats.id ASC;

我返回错误:SQL Error (1111): Invalid use of group function。我认为可以肯定地说问题源于SET nbrSeats = COUNT(Seats.id);因为SET nbrSeats = 5;对于上面的示例输入来说做的很好。我知道可能有更好的方法来解决问题,但由于我仍处于学习阶段的开始,我仍然想了解哪里出了问题。谢谢!

4

1 回答 1

0

要计算 id 使用SELECT COUNT(id) from Seats.

尝试:

DELIMITER //
CREATE PROCEDURE Test() 
  BEGIN
    DECLARE x INT;
    DECLARE nbrSeats INT;
    SET x = 1;
    SET nbrSeats = (SELECT COUNT(id) from Seats);
    WHILE x < nbrSeats DO
        UPDATE Seats
            SET Seats.id = 0
            WHERE Seats.id = x+1;
        UPDATE Seats
            SET Seats.id = x+1
            WHERE Seats.id = x;
        UPDATE Seats
            SET Seats.id = x
            WHERE Seats.id = 0;
        SET x = x+2;
    END WHILE;
  END //
DELIMITER ; 
于 2021-11-15T15:22:25.243 回答