MySQL - 每个类别5个帖子

时间:2018-02-21 12:36:16

标签: mysql sql join jointable

我有这样的架构:

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

posts表格中的每个帖子都有一个或多个类别,只有一个主要类别。

我希望在以下条件下获得每个类别的5个帖子:

  • 所有帖子的年龄必须超过90天

  • 对于每个类别,帖子按DESC中的created_on排序

这就是我的想法,但无法做到正确:

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,它是返回连接表的前5行还是每个类别组的5行?

任何解释都将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:2)

在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会显示查询的结果。

答案 1 :(得分:-1)

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;