【问题标题】:How to SELECT post entries to which latest comment were created with SQL?如何选择使用 SQL 创建最新评论的帖子条目?
【发布时间】:2020-05-28 13:30:32
【问题描述】:

我有表 postcomment 有要发布的外键(post_id)。我想获得 100 个“按顺序排列”的帖子条目。创建最新评论条目的帖子条目排在第一位。我的第一次尝试是:

SELECT * FROM post WHERE id IN
(
    SELECT DISTINCT post_id FROM comment
    ORDER BY created_time DESC
    LIMIT 100
);

返回: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list

第二次尝试:

SELECT * FROM post WHERE id IN
(
    SELECT post_id from
    (SELECT DISTINCT(post_id), posted FROM comment) AS c
    ORDER BY c.created_time DESC
    LIMIT 100
);

这次没有错误,但没有做我想做的事。我怎样才能让 SQL 做我想做的事?

【问题讨论】:

    标签: sql postgresql join greatest-n-per-group


    【解决方案1】:

    如果您要选择 100 个具有最新 cmets 的帖子,您可以使用聚合:

    select p.id, p.title, p.author
    from posts p
    inner join comments c on c.post_id = p.id
    group by p.id, p.title, p.author
    order by max(c.created_at) desc
    limit 100
    

    使用此技术,您需要在select 子句中枚举您希望在结果集中看到的所有postsgroup by 子句中。

    另一种选择是预聚合:

    select p.*
    from posts p
    inner join (
        select post_id, max(created_at) max_created_at
        from comments 
        group by post_id 
        order by max(created_at) desc
        limit 100
    ) c on c.post_id = p.id
    order by c.max_created_at desc
    

    【讨论】:

    • 第一种方法对我有用,但第二种方法没有。但是一个就足够了,谢谢!
    • @RobertC.Holland:您对第二个查询有什么问题?错误,错误的结果?
    • 没有错误,只是错误的结果,结果看起来是按照post id 1到max排序的
    • @RobertC.Holland:是的,我明白了,我在第二个查询中留下了order by。固定。
    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多