2011-12-06 63 views
0

\ d评论PostgreSQL的SQL语句:无法获取所需的最新/最近的评论,需要显示了最新评论

        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; 

独特posts.title我

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) 

但我需要这样

结果0
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) 

与来自三行我需要从职位表中的posts.title三个ID。 我如何编写sql语句来获取post.titt与comments.post_id = 5或8或2?

回答

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; 
+0

我需要得到那些不同的posts.title最新评论。 – shibly

+0

@guru:我已经更新了答案。 –

+0

你为什么使用MAX函数?我需要最新comments.id的结果,这意味着通过created_at创建了comments.id命令。然后我需要内部加入posts.id来获得posts.title。 – shibly