在网页上,我想显示论坛列表(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)
我可以从简单的查询中获取Forums的结果集,在PHP中的数组中循环,然后通过它循环。
我坚持如何创建第二个显示前3个主题的结果集。
我已经阅读了关于Greatest-N-Per-Group的帖子,并尝试过它们,但我认为我的想法增加了一定程度的复杂性。此时我的大脑很难,所以我正在寻求帮助。
我是否创建了一个mysql变量来保存一个以逗号分隔的论坛ID及其子论坛的id列表,然后将其用作IN(1,4,6)语句的值?
或者这是一个糟糕的设计/想法,而且执行成本太高?
我已经在SO上阅读了很多相关的帖子,但是你也可以指出我的任何链接,我也会阅读。
答案 0 :(得分:1)
由于您的问题不够清晰,我不得不做出一些假设,但您应该能够修改它以适合您的表/字段名称。我在最里面的查询中包含了一个基于日期的过滤器,以尝试减少开销。您可能需要修改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
注意:我没有尝试过,因此可能存在语法错误。