SQL Exchange行值

时间:2018-05-31 01:50:29

标签: mysql sql

这是来自leetcode的交换席位问题。

老师想改变邻近学生的座位。 输入:

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

输出:

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

给出解决方案:

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;

我的解决方案:

select 
(Case 
    when mod(id,2) !=0 and id != count(*) then id + 1
    when mod(id,2) !=0 and id = count(*) then id
    else id - 1
 end) as 'id',
 student
from seat
order by id;

给定的解决方案效果很好,但我的只能获得一行输出。

我的输出:

+---------+---------+
|    id   | student |
+---------+---------+
|    2    | Abbot   |
+---------+---------+

任何人都可以解释我的解决方案和给定解决方案之间的区别以及为什么我的解决方案出错了? 感谢。

1 个答案:

答案 0 :(得分:0)

在查询中直接使用count()时,您将始终拥有一行。 另一种解决方案是使用count()作为整个查询的值,使用子查询。

尝试

SELECT id, (SELECT COUNT(*) FROM seat) FROM seat

select from acceso>

+----+---------------+---------------------+-----------+-----------+------------+
| id | ip            | date                | bloqueado | categoria | comentario |
+----+---------------+---------------------+-----------+-----------+------------+
|  1 | 201.214.164.5 | 2018-05-31 01:16:10 |         0 |         1 | NULL       |
+----+---------------+---------------------+-----------+-----------+------------+

select from categoria>

mysql> select * from categoria;
+----+---------+
| id | nombre  |
+----+---------+
|  1 | general |
+----+---------+

并观察其差异。