php - 根据两个条件 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 更简单)?
解决方案
您可以使用 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
推荐阅读
- api - 招摇用户界面 | Nginx 服务器
- php - 如何在php中使数组元素只读
- python - Streamlit Python 应用程序成功部署到 Heroku,但出现应用程序错误
- flutter - Flutter:在父状态更改时重新渲染子小部件
- python - 我无法找到此按钮的 ID,所以它使我无法点击它,我该如何按下它?
- python - 如何更改类 __str__ 方法或从方法中提取值?
- python - 在 pandas DataFrame 中拆分嵌套字典
- processing - 在处理 3 中将代码实现为着色器
- cookies - 如何更改 cookie-universal-nuxt 的同站点策略
- c# - 使用 C# 将大数据写入 MemoryStream