可以更正以下查询

时间:2012-11-02 00:07:17

标签: php sql mysqli

我在查询中需要一些帮助,我不知道我是否包含了正确的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和QuestionMark:

 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

目前如果我在Session“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

1 个答案:

答案 0 :(得分: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