sql - 这个sql查询可以针对oracle数据库优化吗?
问题描述
消息表
|-----|-------------|-----------------|--------|--------------|
| id | message_id | msg_connect_id | body | created_ts |
|-----|-------------|-----------------|--------|--------------|
| 1 | 12345 | 1234 | body1 | timestamp1 |
| 2 | 12346 | 1234 | body2 | timestamp2 |
| 3 | 12347 | 1234 | body3 | timestamp3 |
| 4 | 12348 | 5678 | body4 | timestamp4 |
| 5 | 12349 | 1234 | body5 | timestamp5 |
|-----|-------------|-----------------|--------|--------------|
如果 message_id 是一个查询参数,这个查询可以优化吗?
SELECT id,message_id ,body,created_ts FROM message
where msg_connect_id = (select msg_connect_id from message where message_id ='12346')
and id <= (select id from message where message_id ='12346') order by created_ts desc
我期待与 message_id 参数匹配的行以及它下面具有相同 msg_connect_id 的所有行。因此,例如,如果参数 message_id 是 12346,那么预期的行是 id 为 2、3 和 5 的行。
解决方案
您可以将子查询移动到from
子句并使用索引:
select m.id, m.message_id, m.body, m.created_ts
from message m cross join
(select m2.*
from message m2
where message_id = 12346 -- it looks like a number, so I assume it is
) mm
where m.msg_connect_id = mm.msg_connect_id and
m.id <= mm.id
order by m.created_ts desc;
为此,您需要 和 上的(message_id)
索引(msg_connect_id, id)
。
推荐阅读
- python - 如何在个人资料页面中显示注册人的特定内容 - Django
- java - 在 Java 中实现 LRU 缓存
- reactjs - 尝试从“react-native”导入 AppRegistry 后无法编译未找到的模块
- javascript - 无法安装组件:未定义模板或渲染函数。组件导入失败
- flutter - Flutter FutureBuilder widget not responding to Future resolution when chaining Futures with await
- google-cloud-build - Cloud Build 中的 imageurl 是什么?
- java - 如何从 Java 控制器访问变量?JavaFX,场景生成器
- chatbot - 在没有邀请的情况下作为 Slack 机器人写入直接消息
- reactjs - 在父组件中,有什么方法可以从子组件访问道具?
- node.js - 每个 API 请求都会创建 Express-session 新会话