SQL查询错误的结果

时间:2012-06-19 13:03:54

标签: mysql sql database

我有这个问题:

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(计数器) )应为零。

请帮助我,谢谢你。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

使用a1}}而不是LEFT OUTER JOIN

答案 2 :(得分: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