diff --git a/notes/Leetcode-Database 题解.md b/notes/Leetcode-Database 题解.md index 9bf9bf22..d47a54c9 100644 --- a/notes/Leetcode-Database 题解.md +++ b/notes/Leetcode-Database 题解.md @@ -13,6 +13,7 @@ * [177. Nth Highest Salary](#177-nth-highest-salary) * [178. Rank Scores](#178-rank-scores) * [180. Consecutive Numbers](#180-consecutive-numbers) +* [626. Exchange Seats](#626-exchange-seats) @@ -856,5 +857,87 @@ FROM WHERE L1.id = l2.id - 1 AND L2.id = L3.id - 1 AND L1.num = L2.num - AND l2.num = l3.num; + AND l2.num = l3.num; +``` + +# 626. Exchange Seats + +https://leetcode.com/problems/exchange-seats/description/ + +## Description + +seat 表存储着座位对应的学生。 + +```html ++---------+---------+ +| id | student | ++---------+---------+ +| 1 | Abbot | +| 2 | Doris | +| 3 | Emerson | +| 4 | Green | +| 5 | Jeames | ++---------+---------+ +``` + +要求交换相邻座位的两个学生,如果最后一个座位是奇数,那么不交换这个座位上的学生。 + +```html ++---------+---------+ +| id | student | ++---------+---------+ +| 1 | Doris | +| 2 | Abbot | +| 3 | Green | +| 4 | Emerson | +| 5 | Jeames | ++---------+---------+ +``` + +## SQL Schema + +```sql +DROP TABLE +IF + EXISTS seat; +CREATE TABLE seat ( id INT, student VARCHAR ( 255 ) ); +INSERT INTO seat ( id, student ) +VALUES + ( '1', 'Abbot' ), + ( '2', 'Doris' ), + ( '3', 'Emerson' ), + ( '4', 'Green' ), + ( '5', 'Jeames' ); +``` + +## Solution + +使用多个 union。 + +```sql +SELECT + s1.id - 1 AS id, + s1.student +FROM + seat s1 +WHERE + s1.id MOD 2 = 0 UNION +SELECT + s2.id + 1 AS id, + s2.student +FROM + seat s2 +WHERE + s2.id MOD 2 = 1 + AND s2.id != ( SELECT max( s3.id ) FROM seat s3 ) UNION +SELECT + s4.id AS id, + s4.student +FROM + seat s4 +WHERE + s4.id MOD 2 = 1 + AND s4.id = ( SELECT max( s5.id ) FROM seat s5 ) +ORDER BY + id; ``` diff --git a/notes/SQL.md b/notes/SQL.md index 107156e0..3bbb121f 100644 --- a/notes/SQL.md +++ b/notes/SQL.md @@ -660,7 +660,7 @@ MySQL 不允许在触发器中使用 CALL 语句,也就是不能调用存储 MySQL 的事务提交默认是隐式提交,每执行一条语句就把这条语句当成一个事务然后进行提交。当出现 START TRANSACTION 语句时,会关闭隐式提交;当 COMMIT 或 ROLLBACK 语句执行后,事务会自动关闭,重新恢复隐式提交。 -通过设置 autocommit 为 0 可以取消自动提交,直到 autocommit 被设置为 1 才会提交;autocommit 标记是针对每个连接而不是针对服务器的。 +通过设置 autocommit 为 0 可以取消自动提交;autocommit 标记是针对每个连接而不是针对服务器的。 如果没有设置保留点,ROLLBACK 会回退到 START TRANSACTION 语句处;如果设置了保留点,并且在 ROLLBACK 中指定该保留点,则会回退到该保留点。