1

数据库表结构:

会话表(又名考试表)

SessionId(auto)  SessionName
137              XULWQ

问题表:

SessionId  QuestionId QuestionContent  QuestionNo QuestionMarks  OptionId
137        1          Name 2 Things     1         5               5
137        2          Name 3 Things     2         5               2

Option_Table 表:

OptionId  OptionType
1         A-C
2         A-D
3         A-E
4         A-F
5         A-G
6         A-H

答案表:

 AnswerId(auto) SessionId  QuestionId  Answer
   200            137        1           B
   201            137        1           F
   202            137        2           D
   203            137        2           A
   204            137        2           C   

我在编译下面的查询时遇到问题。我想在查询中选择以下字段,但我遇到的问题是我的联接。如果您查看我试图OptionIDOption_Table表中检索的最后一个连接,但我必须通过Answer没有该字段的表。我的问题是我有 3 个字段实际上依赖于加入问题表。

我的问题是加入下表的正确方法是什么,以便它显示每个问题的答案以及我要选择的字段?

SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionNo, q.QuestionContent, an.Answer, an.AnswerId, q.QuestionMarks, q.OptionId, o.OptionType
       FROM Session s 
       INNER JOIN Question q ON s.SessionId = q.SessionId
       JOIN Answer an ON q.QuestionId = an.QuestionId
       JOIN Option_Table o ON an.OptionId = o.OptionId
       WHERE s.SessionName = ?
       ORDER BY q.QuestionId, an.Answer

需要输出:

在此处输入图像描述

4

3 回答 3

4

只需更改该JOIN条件以使用表中的列Question

SELECT  q.SessionId, s.SessionName, q.QuestionId, q.QuestionNo, 
        q.QuestionContent, an.Answer, an.AnswerId, q.QuestionMarks, 
        q.OptionId, o.OptionType
FROM `Session` s 
INNER JOIN `Question` q 
    ON s.SessionId = q.SessionId
INNER JOIN `Answer` an 
    ON q.QuestionId = an.QuestionId
INNER JOIN `Option` o 
    ON q.OptionId = o.OptionId
WHERE s.SessionName = ?
ORDER BY q.QuestionId, an.Answer
于 2013-01-09T18:42:04.977 回答
2
SELECT * 
FROM Question q 
    INNER JOIN Answer a ON q.QuestionID = a.QuestionID
    INNER JOIN Option_Table ot ON ot.optionID = q.optionID
    INNER JOIN session s ON s.sessionid = q.sessionid
于 2013-01-09T18:44:00.903 回答
1
SELECT
    s.SessionId ,
    s.SessionName,
    q.QuestionId,
    q.QuestionNo,
    q.QuestionContent,
    a.Answer,
    a.AnswerId,
    q.QuestionMarks,
    ot.OptionId,
    ot.OptionType  
FROM    Session as s
LEFT JOIN Question as q ON s.SessionId = q.SessionId
LEFT JOIN Option_Table as ot ON ot.OptionId = q.OptionId 
LEFT JOIN Answer as a ON a.QuestionId = q.QuestionId    
于 2013-01-09T18:43:23.233 回答