伯爵喜欢每篇博客的帖子

时间:2014-04-01 13:15:58

标签: mysql sql inner-join

我确信这个问题的答案是微不足道的,但我已经很长时间了,并且找不到合适的组合。

我有3个表,博客帖子喜欢。我想列出每博客最多喜欢帖子

现在我按照每个帖子计算一下这样的问题,我将这样的查询分组(最后来自同一个博客的多个帖子):

select
  posts.*,
  count(*) as c
from posts
inner join likes
  on posts.id = likes.post_id
group by posts.id

表格之间的关系是:

Blog: id, name
Post: id, name, content, blog_id
Like: id, post_id

2 个答案:

答案 0 :(得分:1)

以下查询获取博客上帖子的赞照数量:

select p.blog_id, count(*) as numlikes
from posts p inner join
     likes l
     on p.id = l.post_id
group by p.blog_id;

获得最大值。 。 。嗯,对于聚合查询来说,MySQL并不是那么有趣。以下是一种使用substring_index() / group_concat()

的方法
select p.blog_id, max(numlikes) as maxnumlikes,
       substring_index(group_concat(p.id order by numlikes desc), ',', 1
                      ) as MostLikedPostId
from (select p.blog_id, p.id, count(*) as numlikes,
      from posts p inner join
           likes l
           on p.id = l.post_id
      group by p.blog_id, p.id
     ) pb;

如果您想了解有关帖子的更多信息,则可以添加其他联接以获取帖子信息。

答案 1 :(得分:0)

  

我想列出每个博客最喜欢的帖子。

假设posts表包含blog_id,我认为这可以满足您的需求:

SELECT p.id AS post_id, p.blog_id, COUNT(1) AS like_count
FROM posts p
INNER JOIN likes l ON (p.id = l.post_id)
GROUP BY p.id, p.blog_id
ORDER BY COUNT(1) DESC

你没有指定你需要的每个博客的最多帖子数量,所以这将按照最喜欢的顺序返回所有帖子,无论帖子来自哪个博客。

如果想要每篇博客的帖子,那么它在MySQL中要复杂得多:

SELECT v.post_id, v.blog_id, v.like_count 
FROM (
    SELECT p.id AS post_id, p.blog_id, COUNT(1) AS like_count
    FROM posts p
    INNER JOIN likes l ON (p.id = l.post_id)
    GROUP BY p.id, p.blog_id
) v
INNER JOIN (
    SELECT MAX(t.like_count) AS like_count, t.blog_id
    FROM (
        SELECT p.id AS post_id, p.blog_id, COUNT(1) AS like_count
        FROM posts p
        INNER JOIN likes l ON (p.id = l.post_id)
        GROUP BY p.id, p.blog_id
    ) t
    GROUP BY t.blog_id
) max_post ON (max_post.like_count = v.like_count AND max_post.blog_id = v.blog_id);

你可以看到这个小提琴,here

警告 - 如果同一博客的两个帖子分享了该博客的最大数量,那么他们将两者出现在结果中。