Mysql Select 特定匹配后的 X 行

Mysql Select X rows after specific match

我正在尝试在 MySQL 中编写一个 select 语句,以便在我得到我的匹配项后获得 5 行,然后对这些数字重复的次数求和。

示例:

原始 Table

id number
1 1
2 0
3 9
4 14
5 11
6 0
7 3
8 4
9 10
10 9
11 0
12 5
13 3
14 11
15 0

我需要找到数字为 0 的每一行,然后是 select 并在之后显示 5 行并计算数字的出现次数。 我怎样才能 select 数字并得到计数结果?

第一个select的结果应该是这样的:

id number
3 9
4 14
5 11
6 0
7 3
7 3
8 4
9 10
10 9
11 0
12 5
13 3
14 11
15 0

上次查询每个数的统计结果

Number Count
9 2
14 1
11 2
0 3
3 3
4 1
10 1
5 1

这是一个获得预期结果的演示:

Select 个数:

SELECT id, number
FROM (
 SELECT b.id, b.number, ROW_NUMBER() OVER(PARTITION BY a.id ORDER BY b.id ASC) r
 FROM numbers a
 JOIN numbers b ON a.id < b.id
 WHERE a.number = 0
) t WHERE t.r <= 5
ORDER BY id

数数:

WITH n AS (
 SELECT id, number
 FROM (
  SELECT b.id, b.number, ROW_NUMBER() OVER(PARTITION BY a.id ORDER BY b.id ASC) r
  FROM numbers a
  JOIN numbers b ON a.id < b.id
  WHERE a.number = 0
 ) t WHERE t.r <= 5
)
SELECT number, COUNT(*) counts
FROM n
GROUP BY number

示例数据:

CREATE TABLE numbers (
id INT PRIMARY KEY auto_increment,
number INT NOT NULL
);

INSERT INTO numbers ( number ) VALUES (1),(0),(9),(14),(11),(0),(3),(4),(10),(9),(0),(5),(3),(11),(0);

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1fe71080cfb27680eb2a37b721e5de2d

更新 MySQL v5.7

SELECT n.*
FROM numbers n
JOIN (
 SELECT a.id, SUBSTRING_INDEX(GROUP_CONCAT(b.id ORDER BY b.id SEPARATOR ','), ',', 5) selections
 FROM numbers a
 JOIN numbers b ON a.id < b.id
 WHERE a.number = 0
 GROUP BY a.id
) t ON FIND_IN_SET(n.id, t.selections)
ORDER BY n.id

SELECT n.number, COUNT(*) counts
FROM numbers n
JOIN (
 SELECT a.id, SUBSTRING_INDEX(GROUP_CONCAT(b.id ORDER BY b.id SEPARATOR ','), ',', 5) selections
 FROM numbers a
 JOIN numbers b ON a.id < b.id
 WHERE a.number = 0
 GROUP BY a.id
) t ON FIND_IN_SET(n.id, t.selections)
GROUP BY n.number
ORDER BY n.number

https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=3be09acab5cd696ec4b01585eb5c32ed