我正在创建一个自定义论坛。我的论坛需要能够显示论坛中的主题数量,最新帖子的主题链接,以及海报简介的链接。为此,我需要每个论坛中的线程数以及最新的帖子。所以我知道我需要什么。问题?我远远不是任何SQL以外的专家" SELECT * FROM table WHERE column = value"
这是我的表,tbl_Forums,schema:
ForumID INT IDENTITY(1,1)
Name NVARCHAR(128) NOT NULL
这是我的tbl_Forum_Threads架构:
ThreadID INT IDENTITY(1,1)
ForumID INT NOT NULL
UserID INT NOT NULL
Name NVARCHAR(128) NOT NULL
最后,我的tbl_Forum_Posts架构:
PostID INT IDENTITY(1,1)
ThreadID INT NOT NULL
UserID INT NOT NULL
Body NVARCHAR(2048) NOT NULL
PostTime DATETIME NOT NULL
因此,考虑到这一点,以下是我一直在努力的视图根本不起作用,因为,Visual Studio甚至无法成功执行此查询(我认为它将是成功调用了一个查询:
CREATE VIEW [dbo].[vw_ForumsAndStats] AS
SELECT
f.*,
COUNT(t.ThreadID) AS NumberOfThreads,
p.PostID AS MostRecentPostID,
p.ThreadID AS MostRecentPostThreadID,
p.UserID AS MostRecentPostUserID
FROM tbl_Forums f
JOIN tbl_Forum_Threads t ON t.ForumID = f.ForumID
RIGHT JOIN tbl_Forum_Posts p ON p.ThreadID IN (SELECT t.ThreadID) AND p.PostID = (SELECT MAX(p.PostID))
答案 0 :(得分:1)
存在几个问题:
类似的东西:
CREATE VIEW [dbo].[vw_ForumsAndStats] AS
SELECT
f.*,
COUNT(t.ThreadID) AS NumberOfThreads,
p.PostID AS MostRecentPostID,
p.ThreadID AS MostRecentPostThreadID,
p.UserID AS MostRecentPostUserID
FROM tbl_Forums f
JOIN tbl_Forum_Threads t ON t.ForumID = f.ForumID
LEFT JOIN (SELECT t.ForumID, MAX(p.PostID) as MaxPostID
FROM tbl_Forum_Posts p
JOIN tbl_Forum_Threads t ON p.ThreadID = t.ThreadID
GROUP BY t.ForumID
) as MostRecentPost ON MostRecentPost.ForumID = f.ForumID
LEFT JOIN tbl_Forum_Posts p ON MostRecentPost.MaxPostID = p.PostID
GROUP BY f.ForumID, F.Name, p.PostID, p.ThreadID, p.UserID
我没有在我面前安装Sql Server,但这应该非常接近。
此外,我将右连接切换为左连接:我假设您的意图是即使他们没有帖子也要显示论坛? (即使没有论坛,右连接也会显示帖子,如果你配置了外键,那就不可能了。)