我的网站上有一个简单的论坛,几乎是完美的。如此接近,但到目前为止......
以下SQL用于创建论坛的首页视图,用户可以在其中查看主题以及回复者的摘要:
SELECT COUNT(forumtopics.forumtopicline) AS totalthreads
, forumtopicline
, forumtopics.whenadded AS threaddate
, forumtopics.whoadded AS author
, forumtopics.title
, COUNT(forumreply.forumtopic) AS replies
, MAX(forumreply.whenadded) AS replydate
, forumreply.whoadded AS replier
FROM forumtopics
LEFT JOIN forumreply ON forumtopicline = forumreply.forumtopic
WHERE forumtopics.topic LIKE '%%'
OR forumtopics.title LIKE '%%'
OR forumreply.reply LIKE '%%'
GROUP BY forumtopicline
ORDER BY
CASE
WHEN COUNT(forumreply.forumtopic) > 0 THEN MAX(forumreply.whenadded)
WHEN COUNT(forumreply.forumtopic) = 0
OR forumreply.forumtopic IS NULL THEN MAX(forumtopics.whenadded)
END
DESC
LIMIT 0 , 30
这项工作几乎完美无缺。这为我提供了线程启动的日期,线程作者和最后一个回复的日期,它正确地将它们排在顶部最新回复的帖子中。
问题在于
MAX( forumreply.whenadded ) AS replydate, forumreply.whoadded AS replier
这会将最后一篇文章的日期返回给帖子,但不管日期如何,都会返回第一个响应者的姓名。我确信必须有一种方法来完成这个相当优雅的SQL,以避免应用程序级操作。任何帮助感激不尽。显然,我需要forumreply.whoadded与MAX在同一行(forumreply.whenadded)
DB = MySQL的。架构:
CREATE TABLE forumtopics (
forumtopicline SERIAL
,title VARCHAR(256)
,topic TEXT
,whenadded DATETIME
,whoadded VARBINARY(128)
,whenaltered DATETIME
,whoaltered VARBINARY(128)
,inuse BOOL
);
CREATE TABLE forumreply (
forumreplyline SERIAL
,forumtopic BIGINT
,reply TEXT
,whenadded DATETIME
,whoadded VARBINARY(128)
,whenaltered DATETIME
,whoaltered VARBINARY(128)
,inuse BOOL
);
答案 0 :(得分:1)
试试这个:
SELECT
totalthreads,
forumtopicline,
threaddate,
author,
title,
replies,
replydate,
(
SELECT
fr.whoadded
FROM
forumreply fr
WHERE
fr.forumtopic = forumtopicline
AND fr.reply LIKE '%%'
AND fr.whenadded = replydate
) as replier
FROM (
SELECT COUNT(forumtopics.forumtopicline) AS totalthreads
, forumtopicline
, forumtopics.whenadded AS threaddate
, forumtopics.whoadded AS author
, forumtopics.title
, COUNT(forumreply.forumtopic) AS replies
, MAX(forumreply.whenadded) AS replydate
, forumreply.whoadded AS replier
FROM forumtopics
LEFT JOIN forumreply ON forumtopicline = forumreply.forumtopic
WHERE forumtopics.topic LIKE '%%'
OR forumtopics.title LIKE '%%'
OR forumreply.reply LIKE '%%'
GROUP BY forumtopicline
ORDER BY
CASE
WHEN COUNT(forumreply.forumtopic) > 0 THEN MAX(forumreply.whenadded)
WHEN COUNT(forumreply.forumtopic) = 0
OR forumreply.forumtopic IS NULL THEN MAX(forumtopics.whenadded)
END
DESC
) as tmp