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

Mysql 从2个不同表检索数据的SQL,mysql,sql,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 */ 答案表 exam_id /* unique ID

我有这两张桌子,即问答

问题表

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 */
答案表

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
我使用ID10来获取字段,但问题是根据答案的数量重复的。这是错误的,我试图做的是询问问题,然后给出相应的答案。像这样的

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

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

你知道我遗漏了什么吗?

看来你在
on
子句中遗漏了一个谓词

 ON exam_question.exam_id = exam_answer.exam_id 
AND exam_question.ref_number = exam_answer.ref_number

根据问题中给出的信息,您似乎希望答案上的
ref\u number
列与问题上的
ref\u number
列相匹配。

虽然这通常被视为表示逻辑,但我需要使用数据库来处理。使用
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

您误解了SQL如何生成结果集。它们是以表格的形式出现的,所有的列都具有相同的含义。是的,这正是重点。根据我的问题,你能给我一个如何执行sql的想法吗?Spencer已经向你指出了连接中的一个错误,这肯定会有所帮助,但我认为你没有提到演示文稿,sql本身不会按照你的要求将问题和答案安排在一个列中。SQL在列中表示数据,您将在其中一些列中故意获得“repitition”(注意,不是!replication)。您是否正在使用PHP?这种单列格式的演示应该由PHP(或您的“演示层”使用的任何东西)执行。嗨,问题是,问题显示的计数与答案的计数相同,所以假设我们有2个问题,每个问题有4个答案,这些问题将显示8次。@user3627265:如果问题中有两行,并且每个问题的答案中有四行匹配,那么我们希望总共返回八行。。。每个答案一行。这是我们期望从查询中得到的结果。(我以为您报告了一个问题,关于某个特定问题的答案与同一考试中的所有问题相匹配。)这是与我的答案最接近的解决方案,我测试了这一个,但问题是如何在单选按钮中显示答案,因为此查询在所有位置都显示once@user3627265--对我来说,这是一个完全不同的问题。你应该就你的实际问题提出一个新问题。如果您使用的是
php
,那么我不推荐使用发布的解决方案。在
表示逻辑中处理逻辑客户端。