Question
Is the set up for foreign keys
I want to do for Answer
Table the correct Idea and how to write SQL on Add foreign key constraint dealing with multiple fields?
Session Table:
SessionId (PK) SessionName
1 AAA
2 AAB
Question Table:
QuestionId(PK) SessionId(PK) QuestionContent
1 1 What is 2+2?
2 1 What is 3+3?
1 2 What is 4+4?
2 2 What is 5+5?
Answer Table:
AnswerId(auto, PK) QuestionId(fk) SessionId(fk) Answer
1 1 1 A
2 1 1 D
3 2 1 C
4 2 1 A
5 1 2 True
6 2 2 A
7 2 2 B
Now the issue I have is with foreign keys with the Answer
Table, I want to know which foreign key is correct to do.
What I have done is that I add a foreign key to the SessionId
which means that if I click on a row's SessionId
, it matches the SessionId
in the Session
Table.
Then I thought I will provide a foreign key on QuestionId
in Answer
Table linking to Question
Table. Problem with this though is that if within a row I click on a QuestionId
, then it will display me all of the rows in the QuestionId
which contains the same QuestionId
. So if I wanted to look up this Answer
:
AnswerId(auto, PK) QuestionId(fk) SessionId(fk) Answer
1 1 1 A
When I click on QuestionId
Foreign key above it outputs this below:
QuestionId(PK) SessionId(PK) QuestionContent
1 1 What is 2+2?
1 2 What is 4+4?
The Answer does not belong to both of these questions, it only belongs to one question but because both QuestionId
are the same, it displays both questions.
So what I am thinking is that I want a foreign key constraint where that if user clicks on the QuestionId
in a row, it will look up both QuestionId
and SessionId
so that it knows that question and session (exam) that answer belongs to so that it outputs below:
QuestionId(PK) SessionId(PK) QuestionContent
1 1 What is 2+2?
My question is that I don't know how to write a foreign key constraint which deals with two fields? Also is the set up of foreign keys for just SessionId
and SessionId and QuestionId
together correct?