我的第一个查询返回thread_id,其中is_root
为真
SELECT thread_id FROM event_comments WHERE e_id = 1 and is_root = true ORDER BY date_posted DESC
然后如何使用thread_id从每个线程获取所有消息?
SELECT * FROM event_comments WHERE thread_id = 'ac7672dd-5465-42ca-a887-273f7641c972' ORDER BY date_posted
SELECT * FROM event_comments WHERE thread_id = '33da63a3-d324-4767-a294-75cdeaf478d8' ORDER BY date_posted
我不确定如何结合这两个查询来获得预期的输出结果
答案 0 :(得分:2)
如果我正确地跟随了您,则可以将exists
与相关的子查询一起使用:
select *
from event_comments e
where exists (
select 1
from event_comments e1
where e1.e_id = 1 and e1.is_root = true and e1.thread_id = e.thread_id
)
order by thread_id, date_posted
exists
比in
安全,因为它可以正确处理null
值。 in
对于null
来说很棘手:如果子查询返回的任何值都是null
,则所有记录将在外部查询中匹配。
修改
要从线程开始,从具有最新消息的线程开始,然后在线程中消息的降序开始排序结果,您可以执行以下操作:
select *
from event_comments e
where exists (
select 1
from event_comments e1
where e1.e_id = 1 and e1.is_root = true and e1.thread_id = e.thread_id
)
order by
max(date_posted) over(partition by thread_id),
date_posted desc
答案 1 :(得分:0)
尝试一下:
SELECT * FROM event_comments WHERE thread_id in (SELECT thread_id FROM event_comments WHERE e_id = 1 and is_root = true) ORDER BY date_posted