数据库表结构:
会话表(又名考试表)
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
我在编译下面的查询时遇到问题。我想在查询中选择以下字段,但我遇到的问题是我的连接。如果你查看最后一个连接,我试图从OptionID
表中检索Option_Table
,但是我必须通过没有该字段的Answer
表。我的问题是我有3个字段实际上依赖于加入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
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
需要输出:
答案 0 :(得分: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
答案 1 :(得分:3)
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
答案 2 :(得分: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