首页 > 解决方案 > 这个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 的行。

标签: sqloracle

解决方案


您可以将子查询移动到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)


推荐阅读