Mysql连接查询两个具有多列但多次冗余的表

时间:2014-11-27 12:25:08

标签: mysql

我有两张这样的表:

studentanswer

stuNum | quizNum | questionId | stuAnswer
------------------------------------------
2012   |    1    |     15     | optiona
2013   |    1    |     15     | optionb
2012   |    2    |     16     | optionc
2012   |    2    |     17     | optiona
2012   |    2    |     18     | optionb

questionquiz

quizNum | questionId | question         | correctAns
----------------------------------------------------
1       |     15     | what is sql      | optiona
2       |     16     | what is web      | optionc
2       |     17     | what is android  | optiona
2       |     18     | what is math     | optionb

我想得到这样的结果:

question        | correctAns | stuAnswer
-------------------------------------
what is web     | optionc    | optionc
what is android | optiona    | optiona
what is math    | optionb    | optionb

我想根据stuNum = 2012获得所有stuAnswer,quizNum = 2

我尝试了这段代码,但它循环了3次

SELECT b.stuNum
     , b.quizNum
     , b.questionId
     , c.question
     , c.correctAns
     , c.markQuiz
     , b.stuAnswer 
  FROM studentanswer b 
  JOIN questionquiz c 
    ON b.quizNum = c.quizNum 
 WHERE b.stuNum = 2012 
   AND c.quizNum = 2

这是我得到的结果:

question        | correctAns | stuAnswer
----------------------------------------
what is web     | optionc    | optionc
what is android | optiona    | optiona
what is math    | optionb    | optionb
what is web     | optionc    | optionc
what is android | optiona    | optiona
what is math    | optionb    | optionb
what is web     | optionc    | optionc
what is android | optiona    | optiona
what is math    | optionb    | optionb

2 个答案:

答案 0 :(得分:2)

你必须加入quizNum和questionId。

JOIN questionquiz c 
    ON b.quizNum = c.quizNum AND
    b.questionID = c.questionID 

答案 1 :(得分:0)

好的,让我们从头开始吧。

选择两个表格,以及要加入它们的内容。 (在这种情况下有两列)

SELECT * FROM studentanswer A 
INNER JOIN questionquiz B
ON A.quizNum = B.quizNum AND A.questionID = B.questionID; 

选择您想要的列以及它们来自

的位置

现在应该列出您正在寻找的所有三列

SELECT B.question, B.correctAns, A.stuAnswer 
FROM studentanswer A 
INNER JOIN questionquiz B
ON A.quizNum = B.quizNum AND A.questionID = B.questionID;

获取特定学生ID

SELECT B.question, B.correctAns, A.stuAnswer 
FROM studentanswer A 
INNER JOIN questionquiz B
ON A.quizNum = B.quizNum AND A.questionID = B.questionID
WHERE A.stuNum = '1234';

现在我们想要显示他们的测验号码

SELECT B.question, B.correctAns, A.stuAnswer 
FROM studentanswer A 
INNER JOIN questionquiz B
ON A.quizNum = B.quizNum AND A.questionID = B.questionID
WHERE A.stuNum = '1234' AND B.quizNum = '1';

那应该是它!

免责声明: 目前未经测试,但应该几乎是100%