选择distinct以删除重复的行?

时间:2014-05-16 17:43:58

标签: mysql greatest-n-per-group

我有一个带帖子和评论表的论坛。我想按最近的评论排序:

select distinct(p.id)
    ,p.title
    ,c.id 
from Posts as p
    ,Comments as c 
where c.post_id = p.id 
order by c.id DESC 
LIMIT 50;

但是每次评论我都会得到一排。我知道我想循环阅读最新的评论并抓住前50个独特的帖子。我只是无法将其转换为SQL。

3 个答案:

答案 0 :(得分:0)

您可以这样做,通过获取每个帖子组的最大评论ID并加入您的帖子表,然后按评论ID进行排序

select p.id, p.title, c.id 
from 
Posts as p
JOIN 
(select max(id) id ,post_id 
  from Comments group by 
  post_id LIMIT 50) c
   ON(c.post_id = p.id)
 order by c.id DESC;

请注意,上面的查询只会为每个帖子组提供最近的评论ID,您无法在子查询中使用*来获取评论的整行,这意味着这不会为每个帖子提供最近的评论如果您在子查询中选择全部

,则发布

编辑此查询将仅使用一个内部查询限制的联接,因此只会加入50个帖子的最近评论及其内部联接,因此它会注意只返回关联如果你看到你的问题的解释计划,那么表现可以很清楚

答案 1 :(得分:0)

select p.id
    ,p.title
    ,c.id 
from Posts as p
    ,Comments as c 
where c.post_id in (
                    select distict (id) 
                    from posts
                   )
order by c.id desc 
limit 50;

谢谢,Gaurav

答案 2 :(得分:0)

这是一个没有子查询的解决方案:

SELECT p.id, p.title, MAX(c.id) AS comment_id
FROM Posts AS p
JOIN Comments AS c 
  ON c.post_id = p.id
GROUP BY p.id
ORDER by comment_id DESC 
LIMIT 50

尽管有子查询,这种方式可能会更快,更具可伸缩性,因为它可以优化限制条款:

SELECT p.id, p.title, MAX(c.id) AS comment_id
FROM Posts p
JOIN (SELECT DISTINCT c.post_id FROM Comments c ORDER BY c.id DESC LIMIT 50) t
ON t.post_id = p.id
JOIN Comments c
  ON c.post_id = p.id
GROUP BY p.id
ORDER BY comment_id DESC

确保Comments(post_id)上有索引。