MySQL - 每个类别 5 个帖子

MySQL - 5 posts per category

我有这样的架构:

Posts (id, title, created_on)
Categories (id, title, description)
Distributions (id, post_id*, category_id, main)

posts table 中的每个 post 都有 1 个或多个类别,其中只有 1 个主要类别。

我想获得每个类别的 5 posts,条件如下:

这是我想到的,但无法正确实现:

SELECT p.title, c.title, c.description FROM posts p, distributions d, categories c
  WHERE p.id = d.post_id
  AND d.category_id = c.id
  AND d.main = 1
  AND ABS(DATEDIFF(NOW(), p.created_on)) > 90
  GROUP BY c.id
  ORDER BY p.created_on DESC
  LIMIT 5;

我不确定 limit 5,是 returns 连接的前 5 行 table 还是每个类别组的 5 行?

如有任何解释,我们将不胜感激。谢谢!

在MySQL中使用会话变量,因为目前它不支持任何分析功能。下面的子查询将为每个 category_title 生成序列号,并使用该列在外部查询中进行过滤。

SELECT  post_title, category_title, description
FROM
    (
        SELECT  p.title AS post_title, 
                c.title AS category_title, 
                c.description 
                @counter := IF(@current_category = c.title, @counter + 1, 1) AS counter,
                @current_category := c.title
        FROM    posts p, distributions d, categories c
        WHERE   p.id = d.post_id
                AND d.category_id = c.id
                AND d.main = 1
                AND ABS(DATEDIFF(NOW(), p.created_on)) > 90
        ORDER   BY p.created_on DESC
    ) s
WHERE   counter <= 5

虽然结构不一样,但是DEMO会显示查询的结果。

select c.id,c.title,p.id,p.title,description,created_on from Categories as c
join Distributions as d on d.category_id = c.id
join Posts as p on p.id = d.post_id 
where ABS(DATEDIFF(NOW(), p.created_on)) > 90
ORDER BY p.created_on DESC
LIMIT 5;