MYSQL 仅统计过去 30 天内回答问题最多的用户

MYSQL 仅统计过去 30 天内回答问题最多的用户

目前我有:

SELECT user.userid, Username, count(answerid) as Answers 
FROM user left outer join answer on user.userid=answer.userid
group by user.userid
order by Answers desc
limit 0,5

这将统计回答问题最多的用户。不过我想将其改为仅统计回答问题最多的前 5 名用户过去 30 天内的问题

答案表有一个名为 date1 的字段,其中包含发布答案的日期。有什么想法吗?非常感谢任何帮助。

答案1

您需要一个 where 子句:

SELECT user.userid, Username, count(answerid) as Answers 
FROM user LEFT OUTER JOIN answer ON user.userid=answer.userid
WHERE answer.date1 >= date_sub(curdate(),interval 30 day)
GROUP BY user.userid
ORDER BY Answers desc
LIMIT 0,5

但是正如其他人所建议的那样,最好在没有外连接的情况下进行查询 - 像这样的事情应该有效:

SELECT user.userid, Username, answer_count.Answers
FROM user,
    (SELECT userid, count(answerid) as Answers FROM answer
     WHERE date1 >= date_sub(curdate(),interval 30 day
     GROUP BY userid) answer_count
WHERE user.userid = answer_count.userid
ORDER BY answer_count.Answers desc
LIMIT 0,5

相关内容