Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 选择distinct以删除重复行?_Mysql_Greatest N Per Group - Fatal编程技术网

Mysql 选择distinct以删除重复行?

Mysql 选择distinct以删除重复行?,mysql,greatest-n-per-group,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。您可以这样做,方法是获取每个帖子组的最大评论id,并加入

我有一个论坛,有帖子和评论表。我想根据最近的评论进行分类:

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。

您可以这样做,方法是获取每个帖子组的最大评论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。您不能在子查询中使用
*
获取评论的整行。这意味着,如果您在子查询中选择all,则不会为每个帖子提供最近的评论

编辑此查询将在内部查询中仅使用一个带限制的联接,因此只有50篇文章的最新评论将被联接,其内部联接将确保只返回关联的文章,此外,如果您看到您的任务的解释计划,则性能会很明显

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这里有一个没有子查询的解决方案:

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
尽管使用了子查询,但这种方法可能会更快,更具可伸缩性,因为它可以在limit子句上进行优化:

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

确保
评论(post\u id)

上有一个索引,您希望返回什么?您希望每篇文章都有一行,每个评论都有自己的一行吗?另外,你想用这个代码做什么?按最近的评论对文章进行排序。我想循环浏览最近的评论,并获取前50篇独特的帖子。你的数据库中有日期/时间栏吗?你犯了SQL新手的一个典型错误<尽管在
(p.id)
周围使用了括号,但code>DISTINCT不适用于一列。但是
DISTINCT
始终适用于选择列表中的所有列。也就是说,如果任何一列有不同的值,整行将被视为一个不同的行。@Mark看一下我的更新答案您肯定需要group by,以防post wise top 50Great这样做-需要post上的索引_id@Mark不幸的是,解释并不能反映极限优化。这是一个你必须运行的。测试速度时,将
SQL\u NO\u缓存
放在
选择
之后,以防止查询缓存影响测试。