I need some help in the query I have where I don’t know if I am including the Correct GROUP BY Clause and selecting the fields from the right tables in the SELECT clause:
Below is the database Tables:
Session Table
SessionId SessionName
1 AAA
2 AAB
Question Table
SessionId QuestionId QuestionContent QuestionMarks
1 1 What is 2+2? 2
1 2 What is 4+4? 3
2 1 What is 10+10 and 11+11? 5
2 2 What is 15+15? 5
2 3 What is 20+20 and 40+40? 7
Answer Table
AnswerId SessionId QuestionId Answer
1 1 1 B
2 1 2 C
3 2 1 A
4 2 1 D
5 2 2 A
6 2 3 D
7 2 3 E
Below is the query:
$query = "SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent, GROUP_CONCAT(DISTINCT Answer SEPARATOR '') AS Answer, q.QuestionMarks
FROM Session s
INNER JOIN Question q ON s.SessionId = q.SessionId
JOIN Answer an ON q.QuestionId = an.QuestionId
WHERE SessionName = "AAB"
GROUP BY an.SessionId, an.QuestionId
";
I want to display each question which belongs to session “AAB”. So it should display QuestionId, QuestionContent, Answer and QuestionMarks like below:
QuestionId QuestionContent Answer QuestionMarks
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
At the moment if I am search for lets say questions in Session “AAB”, it is displaying this below:
QuestionId QuestionContent Answer QuestionMarks
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
1 What is 10+10 and 11+11? AD 5
2 What is 15+15 A 5
3 What is 20 + 20 and 40+40? DE 7
Your answer table has a session ID in it that it looks like you missed in your join. Also you shouldn’t need the DISTINCT in your group_concat, unless your storage of the same answer for the same question/session multiple times is accidental, in which case I would solve that accident instead of coding a work around into the query.