大家好我已经编写了以下查询来组合3个表的结果(tblQuestions,tblReplies,tblTechnology
并显示所需的结果如下
SELECT tech.DatePosted,
tech.QuestionID,
tech.TechnologyName,
tblr3.TechID,
tblr3.QuestionTitle,
tblr3.UserName,
tblr3.ReplyCount,
tblr3.viewCount,
tblr3.date,
tblr3.RepliedName
FROM (SELECT tblr1.DatePosted,
tblr1.QuestionID,
tblr2.TechID,
tblr2.QuestionTitle,
tblr2.UserName,
tblr2.ReplyCount,
tblr2.viewCount,
tblr1.date,
tblr1.RepliedName
FROM (SELECT tblq.DatePosted,
tblq.TechID,
tblq.QuestionID,
tblq.RepliedName,
tblq.QuestionTitle,
tblq.UserName,
tblq.ReplyCount,
tblq.viewCount,
tblq.date
FROM (SELECT q.DatePosted,
q.TechID,
q.QuestionID,
q.QuestionTitle,
q.UserName,
q.ReplyCount,
q.viewCount,
r.date,
r.UserName AS RepliedName
FROM tblQuestions AS q, tblReplies AS r
WHERE r.QuestionID = q.QuestionID
AND r.TechID = q.TechID
AND q.TechID = 1) AS tblq,
(SELECT r.QuestionID,
max(r.date) AS PostedDate
FROM tblReplies AS r
GROUP BY QuestionID) AS tblr
WHERE tblq.QuestionID = tblr.QuestionID
AND tblq.date = tblr.PostedDate) AS tblr1
RIGHT OUTER JOIN
(SELECT q.QuestionID,
q.TechID,
q.UserName,
q.viewCount,
q.ReplyCount,
q.QuestionTitle
FROM tblQuestions AS q
WHERE q.TechID = 1) AS tblr2
ON tblr2.QuestionID = tblr1.QuestionID) AS tblr3
LEFT OUTER JOIN
(SELECT q.QuestionID,
q.DatePosted,
t.TechID,
t.TechName AS TechnologyName
FROM tblTechnology AS t, tblQuestions AS q
WHERE q.TechID = t.TechID) AS tech
ON tblr3.TechID = tech.TechID
AND tblr3.QuestionID = tech.QuestionID
AND tech.TechID = 1
这给了我预期的以下结果,但NULL
在一些数据存在的领域
代替NULL
我需要提取一些存在于 中的数据tblQuestions
,也可以减少查询。
来自 OP 评论:
我正在尝试提取 questiontitle,username,questionid from tblquestions
以及基于来自的技术 IDreplycount and viewcount
为该问题发布的最新回复QuestionID
tblreplys