2012-11-02 29 views
-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,接聽和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 
+0

你還沒有提到你的查詢應該做什麼。您期待的結果表格將有所幫助。 – Laurence

+1

輸出和期望的結果是什麼?在phpmyadmin中玩起來比在猜測中更容易:) – deb0rian

+0

無法通過僅針對聚集函數使用羣組? – Flosculus

回答

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 
+0

嗨,是的,我只是想出了它,與你的答案完全一樣。我即將發佈自己的答案,但幸運地看到了你的答案。無論如何給你最好的答案 – user1789716