SQL从2个不同的表中检索数据

时间:2014-09-16 03:02:23

标签: mysql sql

我有这两个表即问答。

问题表

exam_id /* unique ID
ref_number /* for numbering of question */
value /* the question */

答案表

    exam_id, /*id to connect to question */
    ref_number /*identifier for what question */
    answer /*the value */

我使用此SQL来获取数据库中的字段

SELECT exam_answer.*, exam_question.* FROM exam_question INNER JOIN exam_answer ON exam_question.exam_id = exam_answer.exam_id WHERE exam_question.exam_id =10

我使用ID 10进行了测试以获取字段,但问题是根据答案计数重复。这是错的,我试图做的是查询问题,然后查询相应的答案。像这样的东西。

Question 1
Answer 1,
answer 2,
answer 3
answer 4

Question 2
Answer 1,
answer 2,
answer 3
answer 4

关于我遗失的任何想法?

2 个答案:

答案 0 :(得分:1)

虽然这通常被认为是表示逻辑,但我需要使用数据库来处理它。使用union并创建排序顺序可以处理布局。

select result
from (
  select exam_id, ref_number, value as result, 1 as sort_order
  from question 
  union all
  select exam_id, ref_number, answer as result, 2 as sort_order
  from answer
 ) t
order by exam_id, ref_number, sort_order

答案 1 :(得分:0)

看起来您在ON子句

中缺少谓词
 ON exam_question.exam_id = exam_answer.exam_id 
AND exam_question.ref_number = exam_answer.ref_number

根据您问题中提供的信息,您希望答案中的ref_number列符合问题的ref_number列。