例如,我有一个可以按时间排序的表格。现在我想选择我的数据,例如根据时间取一行,其中 column_x = something 和该行的一些最近的邻居(提前给出的具体数字)。在请求中我想选择多行。让我用一个简单的例子来说明:
+------+----------+----------+
| Time | Column_1 | Column_2 |
+------+----------+----------+
| 1 | 0 | 5 |
| 2 | 0 | 6 |
| 3 | 1 | 9 |
| 4 | 1 | 8 |
| 5 | 0 | 5 |
| 6 | 0 | 8 |
| 7 | 0 | 9 |
| 8 | 0 | 6 |
| 9 | 0 | 4 |
| 10 | 1 | 5 |
| 11 | 0 | 2 |
| 12 | 0 | 3 |
| 13 | 0 | 1 |
+------+----------+----------+
我想选择结果数据,使得 COLUMN_1 = 1 和两个最近的邻居。所以我期待的结果是这张表:
+------+----------+----------+
| Time | Column_1 | Column_2 |
+------+----------+----------+
| 1 | 0 | 5 |
| 2 | 0 | 6 |
| 3 | 1 | 9 |
| 4 | 1 | 8 |
| 5 | 0 | 5 |
| 6 | 0 | 8 |
| 8 | 0 | 6 |
| 9 | 0 | 4 |
| 10 | 1 | 5 |
| 11 | 0 | 2 |
| 12 | 0 | 3 |
+------+----------+----------+
最佳答案
一个解决方案可能是这样,我不知道这是否是最好的:
select
time
,col_1
,col_2
from @tbl
where col_1 = 1
union
select
t2.time
,t2.col_1
,t2.col_2
from @tbl t1
inner join @tbl t2
on t1.time = t2.time-1
or t1.time = t2.time-2
where t1.col_1 = 1
union
select
t2.time
,t2.col_1
,t2.col_2
from @tbl t1
inner join @tbl t2
on t1.time = t2.time+1
or t1.time = t2.time+2
where t1.col_1 = 1
关于mysql - SQL - 如何选择特定行及其最近的邻居?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47527429/