如何 SELECT post 条目的最新评论是用 SQL 创建的?

How to SELECT post entries to which latest comment were created with SQL?

我有表 postcomment,它们具有指向 post 的外键 (post_id)。我想获得 100 "bump ordered" post 个条目。创建最新评论条目的 post 条目排在最前面。我的第一次尝试是:

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

Returns: 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 做我想做的事?

如果您正在寻找 select 有最新评论的 100 个帖子,您可以使用聚合:

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 子句 中枚举要在结果集中看到的所有 posts 列=14=] 子句。

另一种选择是预聚合:

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