Postgresql从结果中选择for循环

时间:2018-04-30 19:27:41

标签: database postgresql for-loop select recursion

我的英语不是最好的,但我会尝试。我有评论和回复的表格,我想从评论中选择parentids LIMIT 10并选择与这些评论相关的回复。

  parentid  |   replyid   |  commentowner  |         commentbody         |        postcreation        
------------+-------------+----------------+-----------------------------+----------------------------
 h0rfizsUF6 | CGTSh5XLCB  | mary@none.com  | anyone want to make flowers | 2018-04-30 21:35:53.502332
            | CGTSh5XLCB  | bob@none.com   | reply to mary about flowers | 2018-04-30 21:39:04.313967
            | CGTSh5XLCB  | mary@none.com  | ok well sign up             | 2018-04-30 21:39:33.376884
 Zasrw8768F | DAeing34355 | james@none.com | Hey everyone!               | 2018-04-30 21:40:44.777557
 Zasr2222F  | DAeingrrrr  | mary@none.com  | yo yo yo all                | 2018-04-30 21:41:33.800034
            | CGTSh5XLCB  | james@none.com | Im signed up already        | 2018-04-30 21:42:03.771954
            | DAeingrrrr  | jimmy@none.com | in what house               | 2018-04-30 21:43:10.992619
(7 rows)

我想要的是什么:

  parentid  |   replyid   |  commentowner  |         commentbody         |        postcreation        
------------+-------------+----------------+-----------------------------+----------------------------
 h0rfizsUF6 | CGTSh5XLCB  | mary@none.com  | anyone want to make flowers | 2018-04-30 21:35:53.502332
            | CGTSh5XLCB  | bob@none.com   | reply to mary about flowers | 2018-04-30 21:39:04.313967
            | CGTSh5XLCB  | mary@none.com  | ok well sign up             | 2018-04-30 21:39:33.376884
            | CGTSh5XLCB  | james@none.com | Im signed up already        | 2018-04-30 21:42:03.771954
 Zasr2222F  | DAeingrrrr  | mary@none.com  | yo yo yo all                | 2018-04-30 21:41:33.800034
            | DAeingrrrr  | jimmy@none.com | in what house               | 2018-04-30 21:43:10.992619

当我得到parentids时,我会带着这个

返回
socialnetwork=# select parentid from comments where commentowner ='mary@none.com' and parentid IS NOT NULL;
  parentid  
------------
 h0rfizsUF6
 Zasr2222F

但我无法通过此回复执行forloop。

ERROR:  more than one row returned by a subquery used as an expression

1 个答案:

答案 0 :(得分:1)

不完全清楚你正在尝试做什么,但也许 如下所示:

with parents as (
    select distinct replyid
    from comments
    where commentowner ='mary@none.com' and parentid IS NOT NULL
)
select C.* from parents P left join comments C on P.replyid = C.replyid
;

这不是十个parentids,但是你的示例表在parentid列中有空值,并且不清楚这些行是如何关联在一起的。 相同的回复列也令人困惑。也许那些应该是parentid,或者是值得纪念的。

在任何情况下,您都可以使用CTE构建您感兴趣的密钥集,然后针对表加入以获取所需的行。