Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL如果特定条件匹配,如何获取最新的行_Sql_Postgresql - Fatal编程技术网

SQL如果特定条件匹配,如何获取最新的行

SQL如果特定条件匹配,如何获取最新的行,sql,postgresql,Sql,Postgresql,我是SQL新手,但我尝试做的是一个评论回复功能。例如,假设您的profile_id为11,并且您评论了一篇post_id为339的文章。如果其他几个人对这篇文章发表了评论,那么我想向你展示你对这篇文章发表评论以来的最新评论。看看下面的第一张图片,你可以看到用户11在中间。我想得到关于这篇文章的最后一条评论,上面说的都是废话,因为用户对它发表了11条评论 这是桌子 如果我是用户11,我只想看到在我评论的同一个线程/帖子上发布的最新评论。这意味着我想看看下面的帖子,上面说的都是些废话,但我只收到我的

我是SQL新手,但我尝试做的是一个评论回复功能。例如,假设您的profile_id为11,并且您评论了一篇post_id为339的文章。如果其他几个人对这篇文章发表了评论,那么我想向你展示你对这篇文章发表评论以来的最新评论。看看下面的第一张图片,你可以看到用户11在中间。我想得到关于这篇文章的最后一条评论,上面说的都是废话,因为用户对它发表了11条评论

这是桌子 如果我是用户11,我只想看到在我评论的同一个线程/帖子上发布的最新评论。这意味着我想看看下面的帖子,上面说的都是些废话,但我只收到我的评论。任何建议都很好。我正在使用Postgres 9.6


这将使用order by按从新到旧的顺序进行订购。由于限制1,它也只会显示1个结果。下一个查询将解决您的问题:

select cr.id, cr.stream_id, cr.comments
from comment_replies cr
where 
cr.id in ( select cr2.id 
           from comment_replies cr2
           where 
           cr2.last_reply_timestamp = (select  max(cr3.last_reply_timestamp)
                                       from comment_replies cr3      
                                       where cr3.stream_id=cr2.stream_id
                                      )
           and cr2.stream_id=cr.stream_id
        )
and cr.stream_id in (select cr2.stream_id 
                     from comment_replies cr2 
                     where cr2.profile_id=11)
select cr.id, cr.stream_id, cr.comments
from comment_replies cr
where 
cr.id in ( select cr2.id 
           from comment_replies cr2
           where 
           cr2.last_reply_timestamp = (select  max(cr3.last_reply_timestamp)
                                       from comment_replies cr3      
                                       where cr3.stream_id=cr2.stream_id
                                      )
           and cr2.stream_id=cr.stream_id
        )
and cr.stream_id in (select cr2.stream_id 
                     from comment_replies cr2 
                     where cr2.profile_id=11)