我有4张桌子
Users
ID
Name
Questions
ID
Question
User_Answers
ID
User_ID
Answer
Question_ID
Correct_Answers
ID
Question_ID
Answer_ID
所以例如,我有这些数据
Users
ID = 3
Name = Jack
ID = 4
Name = Mike
--------------------
Questions
ID = 3
Question = text for a question
ID = 4
Question = text for a question
-----------------
User_Answers
ID = 1
User_ID = 3
Answer = 0
Question_ID = 3
ID = 2
User_ID = 3
Answer = 1
Question_ID = 3
ID = 3
User_ID = 3
Answer = 1
Question_ID = 3
ID = 4
User_ID = 3
Answer = -1
Question_ID = 3
ID = 5
User_ID = 3
Answer = 0
Question_ID = 3
ID = 6
User_ID = 3
Answer = 1
Question_ID = 3
-------------------------
Correct_Answers
ID = 1
Question_ID = 3
Answer = 0
ID = 2
Question_ID = 4
Answer = -1
ID = 3
Question_ID = 5
Answer = 0
我需要sql查询才能让我获得最正确答案的用户
SELECT *
FROM users,correct_answers,questions,user_answers
WHERE correct_answers.answer = user_answers.answer
AND user_answers.question_id = correct_answers.question_id
这不会像我想的那样工作,我需要一个子查询来计算正确答案并得到最大值:(
这是sqlfiddle链接
http://sqlfiddle.com/#!2/b53a7/3
我怎么能这样做?
由于
答案 0 :(得分:0)
Select a.user_id, count(b.ID) as maxAnswers
from user_answers a
inner join correct_answers b on a.answer=b.answer
and a.question_id = b. question_id
group by a.user_id
order by maxAnswers desc
limit 1;
答案 1 :(得分:0)
对于具有最正确答案的用户的表结构查询:
Select sq.User_ID, sq.Name, sum(Correctness) as Most_Correct
from (select ua.User_ID, u.Name, if(ua.Answer = ca.Answer, 1, 0) as
Correctness from Users_Answers ua join Questions q
on ua.Question_ID = q.ID join correct_answers ca
on ua.Question_ID= ca.Question_ID join Users u on ua.User_ID = u.ID) as sq
group by User_ID Desc Order by Most_Correct desc limit 1;
http://sqlfiddle.com/#!2/6aa82/1
您还可以按如下方式创建架构:
用户
ID | Name
问题
ID | Question | Answer
User_Answers
ID | User_ID | Answer | Question_ID
查询具有最正确答案的用户:
Select sq.User_ID, sq.Name, sum(Correctness) as Most_Correct
from (select ua.User_ID, u.Name, if(ua.Answer = q.Answer, 1, 0) as Correctness
from User_Answers ua join Questions q
on ua.Question_ID = q.ID join User u on ua.User_ID = u.ID) as sq
group by User_ID Desc Order by Most_Correct desc limit 1;