mysql - 选择嵌套选择查询的输出和输出 + 'n' 之间的所有行
问题描述
我正在尝试简化我编写的查询,该查询将选择特定的序列号,例如 1,然后选择所有大于并等于输出序列号加“n”的行。例如选择序列号 1 和序列号 5 之间的所有行。数据集有 20k 行,所以我最初不会知道序列号。
select sequence,line_id,direction,stop_id,stop_name
from bus_data.bus_locations as stoplist
where line_id ="39a"
and direction= "Outbound"
and sequence >=
(SELECT sequence
FROM bus_data.bus_locations as depart
where line_id = "39a"
and stop_id= 786
)
and sequence <=
(SELECT sequence + 5
FROM bus_data.bus_locations as arrive
where line_id = "39a"
and stop_id= 786
)
order by sequence;
我目前有一个有效的查询,但由于由同一张表中的三个选择组成,我觉得它效率不高。
Sequence line_id direction stop_id stop_name
19 39a Outbound 786 Embassy of Malta
20 39a Outbound 793 Dawson Street
21 39a Outbound 1808 Morgan Place
22 39a Outbound 7389 Navan Road
23 39a Outbound 7586 National Gallery
24 39a Outbound 7587 Science Gallery
我目前有一个有效的查询,但由于由同一张表中的三个选择组成,我觉得它效率不高。下表显示了上述查询的输出。任何不需要从整个表格中选择的建议都会非常有益。
解决方案
如果我理解正确,您可以使用窗口函数:
select bl.*
from (select sequence, line_id, direction, stop_id, stop_name,
max(case when stop_id = 786 then sequence end) over (partition by line_id) as the_sequence
from bus_data.bus_locations bl
where line_id = '39a'
) bl
where sequence >= the_sequence and
sequence <= the_sequence + 5;
推荐阅读
- gmail-api - Google 登录错误 - API_UNAVAILABLE 在 Gmail 帐户上请求 Gmail 范围
- javascript - 当在 JavaScript 中创建复选框时得到 [object HTMLInputElement]
- azure-devops - Azure 构建管道 - 发布的 zip 文件
- python - 如何通过 Selenium 和 Python 在表格中单击 onclick 事件
- javascript - 计数器达到 0 或复位后的清除间隔
- python - 从输入字符串确定是否为 json_newline 格式
- java - 在我的活动启动开始时滞后
- javascript - 防止元素收缩
- c++ - 从内部系统调用生成调用堆栈
- mysql - 用其他字段唯一值的序号更新表中的字段