【问题标题】:postgresql sql statement: Can't get the desired latest/recent comments, need to display the distinct posts.title with the latest commentspostgresql sql语句:无法获得所需的最新/最近评论,需要显示带有最新评论的不同posts.title
【发布时间】:2011-12-06 15:14:31
【问题描述】:

\d cmets

                                   Table "public.comments"
   Column   |          Type          |                       Modifiers                       
------------+------------------------+-------------------------------------------------------
 id         | integer                | not null default nextval('comments_id_seq'::regclass)
 post_id    | integer                | not null
 name       | character varying(255) | not null
 email      | character varying(255) | not null
 content    | character varying(500) | not null
 created_at | date                   | 
 updated_at | date                   | 
Indexes:
    "comments_pkey" PRIMARY KEY, btree (id)

为此声明

select post_id,created_at from comments order by created_at limit 5;

我明白了

 post_id | created_at 
---------+------------
       5 | 2011-07-11
       5 | 2011-07-11
       5 | 2011-07-11
       8 | 2011-07-11
       2 | 2011-07-17
(5 rows)

但我需要这样的结果

 post_id | created_at 
---------+------------
       5 | 2011-07-11
       8 | 2011-07-11
       2 | 2011-07-17
(3 rows)

如何重写 sql 语句以得到这三行作为结果?

\d 个帖子

                                   Table "public.posts"
   Column    |          Type          |                     Modifiers                      
-------------+------------------------+----------------------------------------------------
 id          | integer                | not null default nextval('posts_id_seq'::regclass)
 title       | character varying(100) | not null
 content     | character varying(500) | not null
 created_at  | date                   | 
 updated_at  | date                   | 
 tags        | character varying(55)  | not null default '50'::character varying
 category_id | integer                | not null default 1
Indexes:
    "posts_pkey" PRIMARY KEY, btree (id)

使用这三行中的三个 id,我需要从 posts 表中获取 posts.title。 如何编写 sql 语句以获取带有 cmets.post_id = 5 或 8 或 2 的 posts.title ?

【问题讨论】:

    标签: sql postgresql group-by


    【解决方案1】:

    编辑:根据评论修改答案。

     SELECT p.title, q.LatestCommentDate
         FROM (SELECT c.post_id, MAX(c.created_at) AS LatestCommentDate
                   FROM comment c
                   GROUP BY c.post_id) q
             INNER JOIN posts p
                 ON q.post_id = p.id;
    

    【讨论】:

    • 我需要用最新的 cmets 获取那些不同的 posts.title。
    • 你为什么使用MAX函数?我需要最新 cmets.id 的结果,这意味着 cmets.id 由 created_at 排序。然后我需要内部加入posts.id来获取posts.title。
    • @guru: max 函数返回每个 post_id 的最新评论日期。
    • 我认为,您不需要 group by 和 MAX 。并且您的 sql 的结果不是按 created_at 列排序的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多