在网页上,我想显示一个论坛列表(parent_id = 0)
对于每个论坛,请在该论坛及其子论坛的组中显示最新(最新)的3个主题

APPLE (Forum)
 iPad3        Apr 12   (Topic from subForum "Tablets")
 Genius Bar   Apr 11   (Topic from Forum "APPLE")
 iPodNano     Apr 10   (Topic from subForum "Portables")
repeat with next forum


MySQL 5.5结构

table FORUMS (contains Forums and subForums, 2 level hierarchy max)
 id (autoinc)
 parent_id (0 if Forum, link to other rows id if subForum)
 name


table TOPICS (a Topic is a child of Forums or subForums)
 id (autoinc)
 forum_id (linked to FORUMS table
 name
 date_added (datetime)


我可以从一个简单的查询中获取论坛的结果集,并放入PHP数组中,然后进行循环。

我停留在如何创建第二个结果集上,以显示前三个主题。

我已经阅读了有关Greatest-N-Per-Group的帖子,并进行了尝试,但是我认为我的想法增加了一定程度的复杂性。此时我的大脑不舒服,所以我正在寻求帮助。

我是否创建mysql变量来保存逗号分隔的论坛ID及其子论坛ID的列表,然后将其用于IN(1、4、6)语句的值?

还是这是一个不好的设计/想法,执行起来太昂贵了?

我已经阅读了许多有关SO的相关文章,但是您也可以指向我的任何链接我也会阅读。

最佳答案

由于您的问题不够清楚,我不得不作一些假设,但您应该可以对其进行修改以适合您的表/字段名称。我在最里面的查询中包含了一个基于日期的过滤器,以试图减少开销。您可能需要修改topics.date_added > (CURRENT_DATE - INTERVAL 1 MONTH)条件,以确保每个论坛组始终有3个条目-

SELECT *
FROM (
    SELECT
        tmp.*,
        @rank := IF(@forum=forum_id, @rank + 1, 1) rank,
        @forum := forum_id
    FROM (
        SELECT
            forums.id AS forum_id,
            forums.name AS forum_name,
            NULL AS subforum_id,
            NULL AS subforum_name,
            topics.name AS topic_name,
            topics.date_added
        FROM forums
        INNER JOIN topics
            ON (forums.id = topics.forum_id)
        WHERE topics.date_added > (CURRENT_DATE - INTERVAL 1 MONTH)
        AND forums.parent_id = 0
        UNION ALL
        SELECT
            forums.id AS forum_id,
            forums.name AS forum_name,
            subforums.id AS subforum_id,
            subforums.id AS subforum_name,
            topics.name AS topic_name,
            topics.date_added
        FROM forums
        INNER JOIN forums subforums
            ON forums.id = subforums.parent_id
        INNER JOIN topics
            ON subforums.id = topics.forum_id
        WHERE topics.date_added > (CURRENT_DATE - INTERVAL 1 MONTH)
        AND forums.parent_id = 0
        ORDER BY forum_id ASC, date_added DESC
    ) tmp, (SELECT @forum:=NULL, @rank:=NULL) initvars
) tmp2
WHERE rank <= 3


注意:我没有尝试过,所以可能存在语法错误。

关于mysql - 将MySQL分组论坛及其子论坛分组为同一组,然后再进行“每组最大”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10133068/

10-14 21:55