我正在尝试在postgres中创建一个查询但我有一个问题,我创建的索引没有被使用。我有两个表conversations
和conversation_items
,它们看起来像这样:
conversations conversation_items
| id | | id | conversation_id | fields |
--------- ------------------------------------------------------
| some_id | | id1 | some_id | { "timestamp": "2017-09-29" }
| other | | id2 | some_id | { "timestamp": "2017-09-28" }
我想得到一个结果,对于给定的会话ID,我得到以下结果,其中项目ID按时间顺序按项目时间戳排序。
| id | some_other_conversation_field | items |
----------------------------------------------------
|some_id | some information about convo | id2,id1 |
这是查询:
select conversations.id, array_to_string(array_agg(conversation_items.id), ',')
from conversations
left join (
select * from conversation_items
order by (conversation_items.fields ->> 'timestamp')) as conversation_items
on conversations.id = conversation_items.conversation_id
WHERE (conversations.id='blab')
group by conversations.id
limit 1;
我尝试使用内部选择运行解释,它按预期工作,并使用了索引。