如何显示每个类别中观看次数最多的帖子?

时间:2018-07-07 15:21:53

标签: php mysql sql mysqli

首先,我不将此代码用于wordpress网站,我希望将其代码放到我自己的网站中。所以现在,我有一个问题要显示每个类别中观看次数最多的帖子,

我有桌子=>帖子

     content || category || views
   -------------------------------
     text 1   |  cat1    |  700
     text 2   |  cat2    |  900  <==== most views in cat 2
     text 3   |  cat2    |  900
     text 4   |  cat1    |  900  <==== most views in cat 1
     text 5   |  cat1    |  800
     text 6   |  cat2    |  800
     text 7   |  cat3    |  700  <==== most views in cat 3
     text 8   |  cat2    |  900
     text 9   |  cat3    |  100
     text10   |  cat1    |  100

我想要这样的输出:

    content || category || views
   -------------------------------
     text 4   |  cat1    |  900
     text 2   |  cat2    |  900
     text 7   |  cat3    |  700

1 个答案:

答案 0 :(得分:2)

将您的表加入到GROUP BY子查询中,该子查询可找到每个类别最受欢迎的帖子:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT category, MAX(views) AS max_views
    FROM yourTable
    GROUP BY category
) t2
    ON t1.category = t2.category AND t1.views = t2.max_views;

如果给定类别可能有多个帖子使用相同数量的视图进行捆绑,那么理想情况下,您应该为我们提供打破常规的逻辑。在这种情况下,上面的查询将返回所有绑定的帖子。

如果您使用的是MySQL 8+,则可以使用ROW_NUMBER(或者可能是RANK函数):

SELECT
    content, category, views
FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY views DESC) rn
    FROM yourTable
) t
WHERE rn = 1;