patternsqlMinor
Database design - many to many
Viewed 0 times
databasedesignmany
Problem
I have one MySQL table which contains:
with about 2000 entries.
I also have another table of users. The goal of each user is to solve all of the questions on the website.
I need to be able to randomly pick about 30 questions that the user hasn't answered yet.
How do you suggest I should store data about the questions the user has already solved?
At first I thought about a table with | user_id | - | question_id | (so each time the user solves a question correctly a new row will be added), but I don't know how I'll be able to pick 30 rows that he hasn't answered yet..
- a question
- 4 possible answers separated by a comma
- a number (0-3) representing the correct answer.
- unique id
with about 2000 entries.
I also have another table of users. The goal of each user is to solve all of the questions on the website.
I need to be able to randomly pick about 30 questions that the user hasn't answered yet.
How do you suggest I should store data about the questions the user has already solved?
At first I thought about a table with | user_id | - | question_id | (so each time the user solves a question correctly a new row will be added), but I don't know how I'll be able to pick 30 rows that he hasn't answered yet..
Solution
Considering that the question is labeled
To get questions that a user with
Or, better if there may be some new questions which do not have defined answers yet
database-design I will offer a solution without that CSV field. Even if you decide to keep it, this may offer some ideas.Questioncontains all possible questions.
Answerhas all possible answers (to any question)
QuestionAnswercontains all QA combinations offered, note that there must exist a default answer for "I do not know".
UserQAcontains questions user answered.
- Note that rule "There can be one and only one correct answer for each question" (IsCorrect = 'Y'), has to be implemented on the application level or as a stored procedure/trigger.
To get questions that a user with
specific_UserId has not yet answeredselect qq.QuestionID
from Question as qq
where not exists (select 1
from UserQA as xx
where xx.QuestionID = qq.QuestionID
and xx.UserID = specific_UserId );Or, better if there may be some new questions which do not have defined answers yet
select distinct qq.QuestionID
from QuestionAnswer as qq
where not exists (select 1
from UserQA as xx
where xx.QuestionID = qq.QuestionID
and xx.UserID = specific_UserId );Code Snippets
select qq.QuestionID
from Question as qq
where not exists (select 1
from UserQA as xx
where xx.QuestionID = qq.QuestionID
and xx.UserID = specific_UserId );select distinct qq.QuestionID
from QuestionAnswer as qq
where not exists (select 1
from UserQA as xx
where xx.QuestionID = qq.QuestionID
and xx.UserID = specific_UserId );Context
StackExchange Database Administrators Q#20866, answer score: 3
Revisions (0)
No revisions yet.