Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL-计算多个表中相关行的数量_Mysql_Join_Group By_Mariadb - Fatal编程技术网

MySQL-计算多个表中相关行的数量

MySQL-计算多个表中相关行的数量,mysql,join,group-by,mariadb,Mysql,Join,Group By,Mariadb,我正在制作一个“测验应用程序”。每个测验都有多个问题(quizComponents),每个问题都有多个答案选项(quizComponents),参与者可以从中选择。答案保存在quizResults表中。我有这些桌子: 测验(quizID,quizTitle) QuizComponents(componentId、quizID、quizQuestion) QuizComponentOptions(optionId、componentId、optionValue) QuizResults(resu

我正在制作一个“测验应用程序”。每个测验都有多个问题(quizComponents),每个问题都有多个答案选项(quizComponents),参与者可以从中选择。答案保存在quizResults表中。我有这些桌子:

  • 测验(quizID,quizTitle)
  • QuizComponents(componentId、quizID、quizQuestion)
  • QuizComponentOptions(optionId、componentId、optionValue)
  • QuizResults(resultId、personId、answerOptionId、componentId)
  • 正确选项(组件ID、选项ID)
我想得到一份所有测验的列表,包括每个测验中的组件总数,以及每个测验中任何给定个人的正确/错误答案的数量。 比如:

quizTitle   total_quiz_components   correct_answers     incorrect_answers   
"Quiz 1"            3                       2                   1
"Quiz 2"            10                      1                   9
下面的查询提供了测验中的所有行,以及每个测验包含的测验组件的总数

SELECT q.quizTitle, count(qc.componentId) AS total_quiz_components FROM Quiz q
    LEFT JOIN QuizComponents qc ON qc.quizId=q.quizId
        GROUP BY q.quizId;

但是我陷入了这种关系的疯狂中。

你需要
基于案例的聚合
来获得正确和错误的答案

SELECT q.quizTitle, 
       count(qc.componentId) AS total_quiz_components ,
       sum ( case when CO.optionId = QR.answerOptionId then 1 else 0 end) as correct_answers,
       sum ( case when CO.optionId <> QR.answerOptionId then 1 else 0 end) as incorrect_answers,
FROM Quiz q
LEFT JOIN QuizComponents qc ON qc.quizId=q.quizId
LEFT JOIN QuizResults QR on 
QR.componentId = QC.componentId
LEFT JOIN CorrectOptions CO
on CO.componentId = QR.componentId
GROUP BY q.quizTitle;
选择q.quizTitle,
将(qc.componentId)计算为总组件,
求和(如果CO.optionId=QR.answerOptionId,则为1,否则为0结束)作为正确答案,
总和(如果CO.optionId QR.answerOptionId为1,则为0结束)作为不正确的答案,
来自测验q
在qc上左键连接QuizComponents qc。quizId=q.quizId
左连接QuizResults QR on
QR.componentId=QC.componentId
左联期权公司
关于CO.componentId=QR.componentId
q.quizTitle集团;