2012-11-08 29 views
0

對不起,問題標題很荒唐。我不知道如何推廣它。SQL:返回來自其他用戶發表的評論後我發表評論我沒有創建

我需要在我沒有創建的帖子留言後發生的評論列表。

我正在使用postgres。我的帖子表結構:

CREATE TABLE posts (
    id integer NOT NULL, 
    parent_id integer DEFAULT (-1), 
    msg character varying(140), 
    user_id integer, 
    create_dte numeric(10,0) DEFAULT 0 
); 

只能有一個級別的評論。原帖 的parent_id爲-1。評論有原始文章的idparent_id

我可以讓我的帖子的評論我沒有創建:

select p1.id, p1.msg 
from posts p1 
where p1.user_id = MY_USER_ID 
and p1.parent_id in (
    select p2.id 
    from posts p2 
    where p2.parent_id = -1 
    and p2.user_id != MY_USER_ID) 

能有人給我如何選擇具有相同parent_id 和更大的create_dte職位提示嗎?

+0

ORDER BY'create_dte' –

+0

這不是完整的查詢。這只是一部分。 –

回答

0

我使用@podiluska答案以上爲出發點此解決方案:

select 
    posts.* 
from 
    posts 
     inner join 
     (
      (
       select h1.parent_id, min(h1.create_dte_timestamp) as min_date 
       from posts h1 
       where 
        h1.parent_id != -1 and 
        h1.user_id = USER_ID and 
        h1.parent_id not in 
        (
         select h2.id 
         from posts h2 
         where h2.id = h1.parent_id and h2.user_id = USER_ID 
        ) 
        group by h1.parent_id 
      ) 
     ) lastpost 
     on posts.parent_id = lastpost.parent_id 

where 
    posts.create_dte_timestamp > lastpost.min_date and 
    posts.user_id != USER_ID 
1
select 
    posts.* 
from 
    posts 
     inner join 
    (
     select parent_id, MAX(create_dte) lastpostdate 
     from posts 
     where user_id=2 
     group by parent_id 
    ) lastpost 
     on posts.parent_id = lastpost.parent_id 
     and posts.create_dte>lastpost.lastpostdate 
+0

謝謝。用這個答案作爲我解決方案的基礎。在信用到期時給予信用的適當方式是什麼? –