我正在编写一个查询,使用以下查询从Stack Overflow Stack Exchange Data Explorer中提取问题和答案:
SELECT Top 2
q.id, q.Title, q.Body q_body, q.parentid qpid, q.AcceptedAnswerId, q.Score q_score, q.AnswerCount, q.Tags, q.viewcount,
answers.parentid aa_pid, answers.id aa_id,
answers.body aa_body, answers.score as aa_score, answers.posttypeid
FROM
Posts answers
INNER JOIN Posts q
ON answers.parentid = q.id
WHERE (answers.id = q.AcceptedAnswerId) AND q.AnswerCount > 2
但是,除了接受的答案之外,我还想提取投票最多的答案。既然如此,我甚至无法理解为什么答案不是一个表。
这是我提出的一个查询,您可以实时查看:
SELECT Id AS [Post Link], Body, Score
FROM (
SELECT TOP 1 Id, Body, Score, DENSE_RANK() OVER(ORDER BY Score DESC) Rank
FROM (
SELECT p.Id, p.ParentId, p.Body, p.Score
FROM Posts p
WHERE p.ParentId = ##QuestionId##
)x
ORDER BY Rank ASC
)x
UNION
SELECT *
FROM (
SELECT Id, Body, Score
FROM (
SELECT a.Id, a.ParentId, a.Body, a.Score FROM Posts a
WHERE a.ParentId = ##QuestionId##
)x
)x
WHERE (SELECT b.AcceptedAnswerId FROM Posts b WHERE b.id = ##QuestionId##) = id
第一个部分找到投票最多的答案,而第二个部分搜索被接受的答案(如果有(。
两者都有点复杂,因为Posts
表是关于答案和问题的。这就是两个嵌套的FROM
s的原因。