我在MySQL上有这样一个表:
ID Name Group
1 One A
2 Two B
3 Three A
4 Fore C
5 Five B
6 Six A
7 Seven B
我想从我选择的行中获得同一组中的上一行/下一行。就像我选择ID = 5的行一样,现在当我没有关于该行的任何信息并且与下一行(ID = 7)相同时,如何才能获得同一组的上一行(ID = 2)。
答案 0 :(得分:1)
您正在寻找Windows function
的{{3}}或LEAD,但受支持的mysql高于8.0版本。因此您可以在select
看起来像这样。
TestDLL
CREATE TABLE T(
ID int,
Name VARCHAR(100),
`Group` VARCHAR(5)
);
INSERT INTO T VALUES (1,'One','A');
INSERT INTO T VALUES (2,'Two','B');
INSERT INTO T VALUES (3,'Three','A');
INSERT INTO T VALUES (4,'Fore','C');
INSERT INTO T VALUES (5,'Five','B');
INSERT INTO T VALUES (6,'Six','A');
INSERT INTO T VALUES (7,'Seven','B');
查询
select *,IFNULL((
SELECT t2.ID
FROM T t2
WHERE t1.Group = t2.Group and t1.ID > t2.ID
ORDER BY t2.ID DESC
LIMIT 1
),t1.ID)previousID
,IFNULL((
SELECT t2.ID
FROM T t2
WHERE t1.Group = t2.Group and t1.ID < t2.ID
ORDER BY t2.ID
LIMIT 1
),t1.ID) nextID
from T t1
[结果] :
| ID | Name | Group | previousID | nextID |
|----|-------|-------|------------|--------|
| 1 | One | A | 1 | 3 |
| 2 | Two | B | 2 | 5 |
| 3 | Three | A | 1 | 6 |
| 4 | Fore | C | 4 | 4 |
| 5 | Five | B | 2 | 7 |
| 6 | Six | A | 3 | 6 |
| 7 | Seven | B | 5 | 7 |
如果您的mysql支持Windows功能,则可以尝试此操作。
select *,
LAG(ID)previousID,
LEAD(ID) nextID
from T