我正在努力为我的Q& A网站提供最佳查询。作为一个简化的例子,我有3个表(问题,答案和用户):
table_users
UserID FirstName
1 John
2 Jack
3 Ana
4 Mary
table_questions 。
QuestionID fkUserID Title
1 4 What is...?
2 2 Where is...?
3 1 How to...?
4 3 How much...?
table_answers
AnswerID fkQuestionID fkUserID Answer
1 1 3 It is...
2 2 1 It is located in ZZ...
3 2 4 It is located in YY...
4 3 2 You have to...
我正在创建一个新闻源:
到目前为止,我在下面创建了这个查询:
我遇到了一些性能/速度问题而且我无法只显示问题的最后一个答案(问题2),在这种情况下,DISTINCT选择无法正常工作。
SELECT
DISTINCT (A.fkQuestionID) as QuestionID,
Q.Title,
A.AnswerID as AnswerID,
A.Answer,
U1.FirstName as AnswerFirstName,
Q.pkQuestionID,
U2.FirstName as QuestionFirstName
FROM table_answers as A
INNER JOIN table_questions as Q ON Q.QuestionID=A.fkQuestionID
INNER JOIN table_users as U1 ON U1.UserID=A.fkUserID
INNER JOIN table_users as U2 ON U2.UserID=Q.fkUserID
ORDER BY A.AnswerID DESC
我想将预期结果返回为:
QuestionID AnswerID AnswerFirstName QuestionFirstName
3 4 Jack John
2 3 Mary Jack
1 1 Ana Mary
非常欢迎任何帮助。提前谢谢!
答案 0 :(得分:2)
您可以在子查询中使用MAX
并执行JOIN
以获取所需的列:
SELECT
q.QuestionID,
q.title,
u1.FirstName AS Asker,
a.AnswerID,
a.answer,
u2.FirstName AS Answerer
FROM table_questions q
INNER JOIN table_users u1
ON u1.UserID = q.fkUserID
INNER JOIN (
SELECT
fkQuestionID, MAX(AnswerID) AS AnswerID
FROM table_answers
GROUP BY fkQuestionID
) t
ON t.fkQuestionID = q.QuestionID
INNER JOIN table_answers a
ON a.AnswerID = t.AnswerID
AND a.fkQuestionID = t.fkQuestionID
INNER JOIN table_users u2
ON u2.UserID = a.fkUserID
如果您希望包含没有答案的问题,请将INNER JOIN
替换为LEFT JOIN
。
答案 1 :(得分:1)
您可以按fkQuestionID
分组以获取max(AnswerID)
,然后在join
之后使用它。
SELECT
q.QuestionID,
q.Title,
a1.AnswerID as AnswerID,
a1.Answer,
U1.FirstName as AnswerFirstName,
q.pkQuestionID,
U2.FirstName as QuestionFirstName
FROM
(SELECT MAX(AnswerID) as AnswerID,fkQuestionID FROM table_answers GROUP BY fkQuestionID ) as a2
INNER JOIN table_answers a1 ON a1.fkQuestionID = a2.fkQuestionID AND a1.AnswerID = a2.AnswerID
INNER JOIN table_questions q ON q.QuestionID = a2.fkQuestionID
INNER JOIN table_users as U1 ON U1.UserID=a1.fkUserID
INNER JOIN table_users as U2 ON U2.UserID=q.fkUserID
ORDER BY a2.AnswerID DESC
答案 2 :(得分:0)
Plz试试这个
SELECT QuestionID ,fkUserID,title,ANS.Answer
FROM table_questions QST
INNER JOIN (SELECT fkQuestionID,MAX(AnswerID) AnswerID
FROM table_answers
GROUP BY fkQuestionID) ANS ON ANS.fkQuestionID = QST.QuestionID
INNER JOIN table_answers LANS ON LANS.AnswerID = ANS.AnswerID