【问题标题】:SQL: return comments from other users that occur after my comment on a post I didn't createSQL:在我对我没有创建的帖子发表评论后返回来自其他用户的评论
【发布时间】:2012-11-08 09:13:51
【问题描述】:

抱歉,这个荒谬的问题标题。我不知道如何概括它。

我需要在我的 cmets 离开我没有创建的帖子后出现的 cmets 列表。

我正在使用 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
);

只能有一个级别的 cmets。原创帖子 parent_id 为 -1。评论具有原始帖子的id 的parent_id。

我可以在不是我创建的帖子上获取我的 cmets:

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?

【问题讨论】:

  • 这不是完整的查询。这只是一部分。

标签: sql postgresql subquery


【解决方案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

【讨论】:

  • 谢谢。将此答案用作我的解决方案的基础。在到期时给予信用的适当方式是什么?
【解决方案2】:

我使用上面@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 2011-11-05
    • 2012-01-22
    • 2017-07-07
    • 2019-05-26
    相关资源
    最近更新 更多