sql exchange行值

wnrlj8wa  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(336)

这是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   |
+---------+---------+

有人能解释一下我的解决方案和给定的解决方案有什么区别,为什么我的解决方案是错误的吗?谢谢。

yyyllmsg

yyyllmsg1#

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

SELECT id, count(*) FROM seat

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

观察差异。

相关问题