-1

我在查询中需要一些帮助,但我不知道是否包含正确的 GROUP BY 子句并从 SELECT 子句中的正确表中选择字段:

下面是数据库表:

会话表

SessionId  SessionName
1          AAA
2          AAB

问题表

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

答案表

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

以下是查询:

   $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
   ";

我想显示属于会话“AAB”的每个问题。所以它应该显示 QuestionId、QuestionContent、Answer 和 QuestionMarks,如下所示:

 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

目前,如果我在“AAB”会话中搜索让我们说问题,它会在下面显示:

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
4

1 回答 1

1

您的答案表中有一个会话 ID,看起来您在加入时错过了它。此外,您不应该在 group_concat 中使用 DISTINCT,除非您为同一个问题/会话多次存储相同的答案是偶然的,在这种情况下,我会解决该事故,而不是在查询中编写解决方法。

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
             AND an.sessionID = s.sessionID
WHERE SessionName = "AAB"
GROUP BY an.SessionId, an.QuestionId
于 2012-11-02T01:02:47.260 回答