postgreSQL不按顺序排序

我有这个 postgreSQL 查询,它应该返回

由 comment_date 排序的前 3 条评论来自

按 post_date 排序的前 10 个帖子表...

出于某种原因,它不是按 post_date 订购的:

with a as 
      (
          SELECT  
           posts.post_id as post_id 
          FROM posts where user_id = 'user1'
          order by post_date desc --this is not working
          limit 10
      ), b as
      (
          select user_id,
          comment_id,
          post_id,
          comment_date
          , ROW_NUMBER() over (partition by post_id order by comment_date desc) as RowNum
          from post_comments
      ) 
        SELECT * from a 
     INNER JOIN b USING (post_id)
      where b.RowNum <= 3

示例:https : //extendsclass.com/postgresql/434e9d2

在示例中,它应该获取具有最高 post_date 的帖子,例如 post3>post2>post1

但是帖子的排序不起作用......

我是 postgreSQL 的新手,所以我不知道发生了什么......实际上我从一个 stackoverflow 答案中得到了那个查询,只是稍微编辑了一下:答案

感谢您的回答并为我的英语不好而感到抱歉

回答

订购很好。我怎么知道?外部查询没有order by. 如果没有order by,结果可以按任何顺序排列。

如果您希望按特定顺序获得结果,那么您需要明确

SELECT * 
FROM a JOIN
     b USING (post_id)
WHERE b.RowNum <= 3
ORDER BY a.post_date DESC;

注意:您需要包含post_dateaCTE 中。


以上是postgreSQL不按顺序排序的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>