|-----|-------------|-----------------|--------|--------------|
| 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的行。
答案 0 :(得分:0)
您可以将子查询移至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)
上建立索引。