MySQL查询连接两个具有相似数据的表

时间:2018-03-09 09:50:35

标签: mysql

我有一个MySQL表,如下所示:

questions_table:

questionID, question, optionID, optionText
   '1',    'question1', 100,   'option1',
   '2',    'question2', 200,   'option2',
   '3',    'question3', 300,   'option3',
   '3',    'question3', 400,   'option4',
   '3',    'question3', 500,   'option5',
   '4',    'question4', 600,   'option6'

answers_table:

questionID answeredOptionID
   '1'      '100'      
   '2'      '200'
   '3'      '400'
   '4'      '600'

我需要像这样加入这两个表:

questionID, question, optionID, optionText answeredOptionID
   '1',    'question1', 100,   'option1',        '100'
   '2',    'question2', 200,   'option2',        '200'
   '3',    'question3', 300,   'option3',         Null
   '3',    'question3', 400,   'option4',        '400'
   '3',    'question3', 500,   'option5',         Null
   '4',    'question4', 600,   'option6'         '600'

请帮我查询一下。简单的JOIN或LEFT,RIGHT JOIN不起作用 - 我得到了答案的副本而不是我需要的Nulls

3 个答案:

答案 0 :(得分:1)

您应该在questionID和optionID上使用左连接

select a.questionID, a.question, a.optionID, a.optionText, b.answeredOptionID 
from questions_table a 
left join  answers_table b on a.questionID = b.questionID 
         and a.optionID = b.answeredOptionID 
ORDER BY questTbl.optionID

用于选中或未选中

select a.questionID, a.question, a.optionID, a.optionText, 
 case when b.answeredOptionID is not null then'Checked' ELSE 'Not checked' END result 
from questions_table a 
left join  answers_table b on a.questionID = b.questionID 
         and a.optionID = b.answeredOptionID 
ORDER BY questTbl.optionID

答案 1 :(得分:1)

解决您的问题:

SELECT questTbl.questionID, questTbl.question, questTbl.optionID,
questTbl.optionText, ansTbl.answeredOptionID 
FROM questions_table questTbl 
LEFT JOIN answers_table ansTbl 
ON questTbl.questionID = ansTbl.questionID
AND questTbl.optionID= ansTbl.answeredOptionID
ORDER BY questTbl.optionID

对于演示,请点击以下链接:

  

http://sqlfiddle.com/#!9/fd09e0/5

答案 2 :(得分:0)

select questions_table.questionid,questions_table.question,optionid,
questions_table.optiontext,answers_table.answeredOptionID
from questions_table inner join answers_table
on questions_table.questionID=answers_table.questionID

检查 - http://sqlfiddle.com/#!9/fd09e0/10