Reputation: 125
I build quiz/test application. It has 2 tables in database.
First one, Quiz table:
quizes
--------
title
.....
questions
Questions structure
{
"answer": "rightanswer",
"index": 0,
"question": "What is the right answer?",
"answers": [
"answers1",
"answers2",
"answers3",
"answers4"
],
}
And I have separate table to store users answers (user_answers).
user_answers
-----
id
quiz_id
.....
answers
So, my question is, what is the right way to store user answers.
First way:
Once user open quiz page copy all questions to user_answers/answer column. And just push into question his answer and mark, and then update user_answers/answer.
Second way
Once user open quiz page init blueprint json:
{
"index": 0
"mark": 5
}
After answer on push this json to array and update user_answers/answer, and every time just merge questions and answers arrays like:
for (let i = 0; i < questions.length; i++) {
for (let j = 0; j < userAnswers.length; j++) {
if (userAnswers[j].index == i) {
questions[i].mark = userAnswers[j].mark;
}
}
}
Both of ways have disadvantages In first one you have to make copy of questions a lot of times. In second one loop will take a lot of time if quiz has many questions.
So what is the right way?
Upvotes: 1
Views: 1640
Reputation: 278
I can suggest a better a way to store your questions, Lets say you have a question schema:
{
"qid" : 0,
"question": "What is the answer",
"answers": [
{ "text" : "Answer one" , "isAnswer" : false },
{ "text" : "Answer two" , "isAnswer" : false },
{ "text" : "Answer three" , "isAnswer" : true }
]
}
And for answers schema
{
"quizId" : 10,
"qid" : 0,
"answerId" : 0 // <- here index , but you can take unique answer ids also for a question
}
this way you just need run one loop to get the answers , or write a little complex aggregate query to get the answers
Upvotes: 2
Reputation: 21513
i'd probably just have a table like
CREATE TABLE `answers` (
`id` INTEGER NULL AUTO_INCREMENT,
`user_id` INTEGER,
`quiz_id` INTEGER,
`quiz_question_id` INTEGER,
`answer` VARCHAR(200),
PRIMARY KEY (`id`)
);
CREATE UNIQUE INDEX no_duplicate_answers ON answers (user_id,quiz_id,quiz_question_id);
Upvotes: 0
Reputation: 13
It depends on you, besides I prefer the later, your second solution is a loop and it's happening on the client's machine, so it's not too important! I think it's fast enough to generate 1000 question less than a second so it's ok!
Upvotes: 0