Postgres-结合这两个查询

时间:2019-06-14 06:50:04

标签: sql postgresql

我的第一个查询返回前10个消息ID:

SELECT * from message WHERE $1 IN (creator_id, recipient_id) 
AND parent_id is null 
ORDER BY date_posted 
DESC FETCH FIRST 10 ROW ONLY

[1、2、4、6、10、14、17、18、19、23]

使用每个message_id,第二个查询将获得message_id及其线性树的最大值:

With RECURSIVE recursetree AS
(
  SELECT * FROM message WHERE message_id = $1
  UNION ALL
  SELECT t.*
  From message t
  JOIN recursetree rt ON rt.message_id = t.parent_id                                                        
 )
 SELECT * from recursetree where parent_id is not distinct 
 from (select max(parent_id) from recursetree)

将这两个查询组合在一起只会得到一行,这是最后一个message_id为23的线性树的最大值。我将如何获得所有行?

with RECURSIVE cte as 
(
    (
    SELECT * from message WHERE $1 IN (creator_id, recipient_id) 
    AND parent_id is null ORDER BY date_posted DESC 
        FETCH FIRST 10 ROW ONLY
    )
    UNION
    SELECT t.*
    From message t
    JOIN cte rt ON rt.message_id = t.parent_id
)
SELECT * FROM cte where parent_id is not distinct 
     from (select max(parent_id) from cte)

enter image description here

1 个答案:

答案 0 :(得分:1)

如果要获取每个消息的最新消息, 我认为您应该提取没有孩子的数据。

select m.* 
  from message m
  left join message child on m.message_id = child.parent_id
 where child.message_id is null