我有一个尴尬的 mySQL 查询要进行,并且由于数据库结构不佳(我几年前就做到了)而苦苦挣扎:/
我有 3 张桌子forum_list
,forum_topics
和forum_replies
。我正在通过 forum_list 表循环,显示名称,并且我想获取每个帖子中最后一篇文章的日期和 author_id。
问题是,最后一个帖子可能是 中的回复forum_replies
,也可能是主题forum_topics
我需要一个子查询还是什么?
桌子forum_list
id name
1 General Chat
桌子forum_topics
id forum author date
1 1 John 2012-12-12 12:12:12
桌子forum_replies
id forum topic author date
1 1 1 John 2012-12-12 12:12:12
更新
SELECT forum_list.id
, GREATEST(forum_topics.date, forum_replies.date) date
, CASE GREATEST(forum_topics.date, forum_replies.date)
WHEN forum_topics.date THEN MAX(forum_topics.author)
WHEN forum_replies.date THEN MAX(forum_replies.author)
END author
FROM forum_list
LEFT JOIN (
SELECT forum_topics.id
, max(forum_topics.date) date
FROM forum_topics
GROUP BY forum_topics.forum
) forum_topics_max
ON forum_list.id = forum_topics_max.id
LEFT JOIN forum_topics
ON forum_topics_max.id = forum_topics.id
AND forum_topics_max.date = forum_topics.date
LEFT JOIN (
SELECT forum_replies.id
, max(forum_replies.date) date
FROM forum_replies
GROUP BY forum_replies.topic
) forum_replies_max
ON forum_list.id = forum_replies_max.id
LEFT JOIN forum_replies
ON forum_replies_max.id = forum_replies.id
AND forum_replies_max.date = forum_replies.date
GROUP BY forum_list.id