You have three tables:
- QUESTIONS (QID, QTYPE, ...)
- ANSWERS (AID, QID, ...)
- USER_ANSWERS (UAID, QID, AID, UID (user ID), ...)
In case of possible multi-answers to a question, there will be more than one answer ("check all that applies" type of question) in ANSWERS, and user can check many, resulting many references to same (QID, UID) but with different AID in USER_ANSWERS. In case of one selection allowed, there will be more than one answer in ANSWERS, but user can only select one, resulting a single reference to (QID, UID) in USER_ANSWERS.
My suggestion would be the following - to force at the database level
- Introduce a new column in ANSWERS: AQ_REF (Answer Question Reference). This is populated with QID when the type of question allows only single answer, and with AID when the type of question allows more than an answer
- Use this in addition to AID in USER_ANSWERS
So now, you have the table structure like this:
- QUESTIONS (QID, QTYPE, ...) -- PRIMARY KEY (QID)
- ANSWERS (AID, QID, AQ_REF, ...) -- PRIMARY KEY(AID), FOREIGN KEY(QID), UNIQUE(AID, AQ_REF), CHECK AQ_REF IN (AID, QID)
- USER_ANSWERS (UAID, AID, AQ_REF, UID, ...) -- PRIMARY KEY(UAID), FOREIGN KEY(AID, AQ_REF) REFERENCES ANSWERS(AID, AQ_REF), UNIQUE(AQ_REF, UID)
Example Data:
QUESTIONS:
QID, QTYPE
Q1, 'S' -- for single answer
Q2, 'M' -- for multi answers
ANSWERS:
AID, QID, AQ_REF
A1, Q1, Q1 -- note this has AQ_REF = Q1 as for all Q1 answers
A2, Q1, Q1
A3, Q1, Q1
A4, Q2, A4 -- note this has AQ_REF = A4
A5, Q2, A5 -- note this has AQ_REF = A5
A6, Q2, A6 -- note this has AQ_REF = A6
USER_ANSWERS:
UAID, AID, AQ_REF, UID
UA1, A1, Q1, U1
UA2, A4, A4, U1
UA3, A6, A6, U1