1

我有这个查询:

SELECT `completed`.`ID` AS `ID`,`completed`.`level` AS `level`,`completed`.`completed_in` AS `completed_in`, COUNT(1) AS `right_answers_num` 
FROM `completed` 
INNER JOIN `history` ON `history`.`ID` = `completed`.`ID` 
INNER JOIN `questions` ON `questions`.`ID` = `history`.`question`
WHERE `completed`.`student_id` = '1' AND `questions`.`answer` = `history`.`answer`       
GROUP BY `completed`.`ID` 
ORDER BY `completed`.`completed_in` DESC

我需要的是获取已完成表中每个测试的信息(id、level、completed_in、right_answer_num)
该查询的问题是,如果没有一个正确答案(history.answer = questions.answer),那么它不会返回该行,而它应该返回该行(id,level,completed_in)并且right_answer_num(counter)应该为零..

请帮助我,谢谢。

4

3 回答 3

4
SELECT 
    completed.ID AS ID,
    completed.level AS level,
    completed.completed_in AS completed_in, 
    COUNT(questions.answer) AS right_answers_num 
FROM completed
        INNER JOIN history  ON history.ID = completed.ID
        LEFT JOIN questions ON questions.ID = history.question AND questions.answer = history.answer
WHERE 
    completed.student_id = '1'  
GROUP BY 
completed.ID 
ORDER BY completed.completed_in DESC
于 2012-06-19T13:10:50.937 回答
1

使用LEFT OUTER JOIN一个INNER JOIN.

于 2012-06-19T13:08:17.797 回答
0

第二个内部连接是导致问题表中没有记录的行被省略的原因。内连接只会返回在所有对应表中都有数据的行。将第二个内连接更改为左连接,如下所示:

SELECT 
    completed.ID AS ID,
    completed.level AS level,
    completed.completed_in AS completed_in, 
    COUNT(questions.answer) AS right_answers_num 
FROM completed
INNER JOIN history ON history.ID = completed.ID 
LEFT JOIN questions ON questions.ID = history.question
WHERE completed.student_id = 1       
GROUP BY completed.ID 
ORDER BY completed.completed_in DESC
于 2012-06-19T13:08:38.577 回答