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
php
,那么我不推荐使用发布的解决方案。在表示逻辑中处理逻辑客户端。