首页 > 解决方案 > 根据两个条件 SQL 获取某行上方和下方(相邻行)的行

问题描述

假设我有一张这样的桌子:

+---+-------+------+---------------------+
|id | level |score |      timestamp      |
+---+-------+------+---------------------+
| 4 |   1   |  70  | 2021-01-14 21:50:38 |
| 3 |   1   |  90  | 2021-01-12 15:38:0  |
| 1 |   1   |  20  | 2021-01-14 13:10:12 |
| 5 |   1   |  50  | 2021-01-13 12:32:11 |
| 7 |   1   |  50  | 2021-01-14 17:15:20 |
| 8 |   1   |  55  | 2021-01-14 09:20:00 |
| 10|   2   |  99  | 2021-01-15 10:50:38 |
| 2 |   1   |  45  | 2021-01-15 10:50:38 |
+---+-------+------+---------------------+

我想要做的是在一个表中显示其中的 5 行(在 html 中),中间有某一行(例如 id=5),并在其上方和下方有两行(以正确的顺序)。还有级别= 1。这就像一个计分板,但只显示用户的分数,上面两个,下面两个。所以因为分数可以相同,所以还需要使用时间戳列——所以如果两个分数相等,那么第一个获得分数的人会显示在另一个人的上方。

例如说用户是 id=5,我想显示

+---+-------+------+---------------------+
|id | level |score |      timestamp      |
+---+-------+------+---------------------+
| 4 |   1   |  70  | 2021-01-14 21:50:38 |
| 8 |   1   |  55  | 2021-01-14 09:20:00 |
| 5 |   1   |  50  | 2021-01-13 12:32:11 |
| 7 |   1   |  50  | 2021-01-14 17:15:20 |
| 2 |   1   |  45  | 2021-01-15 10:50:38 |
| 1 |   1   |  20  | 2021-01-14 13:10:12 |
+---+-------+------+---------------------+

注意 id=7 低于 id=5

我想知道有人知道这样做的方法吗?

我在下面尝试过,但它没有输出我需要的东西(它输出的地方 level_id=2 和 id=5,其他行不按顺序排列)

((SELECT b.* FROM table a JOIN table b ON b.score > a.score OR (b.score = a.score AND b.timestamp < a.timestamp)
  WHERE a.level_id = 1 AND a.id = 5 ORDER BY score ASC, timestamp DESC LIMIT 3)
 UNION ALL 
 (SELECT b.* FROM table a JOIN table b ON b.score < a.score OR (b.score = a.score AND b.timestamp > a.timestamp)
  WHERE a.level_id = 1 AND a.id = 5 ORDER BY score DESC, timestamp ASC LIMIT 2)) 
order by score 

如果更容易输出表中的所有行,说哪里 level = 1,所以它是一个满分板.. 然后使用 PHP 获取某一行和上下两行我也想知道请 :) !(可能认为这可能会使 SQL 更简单)?

标签: phpjoinmariadbunion

解决方案


您可以使用 cte 和内部连接,如下所示:

With cte as
(select t.*,
        dense_rank() over (order by score) as dr
   from your_table t)
Select c.*
  From cte c join cte cu on c.dr between cu.dr - 2 and cu.dr + 2
 Where cu.id = 5
Ordwr by c.dr, c.timestamp

推荐阅读