如何使用连接从三个表中选择数据
我想从以下三个表中选择survey_id
,question_id
,question_text
和answer_id
。如何使用连接从三个表中选择数据
在SurveyTable我:
Survey{survey_id,survey_title}
在QuestionTable我:
Question{survey_id,question_id,question_text}
在AnswerTable:
Answer{question_id,answer_id,answer_text}
我想用连接这些表来选择。当survey_id
等于QuestionTable和SurveyTable中的值时。
好了,你可以用的东西开始像
SELECT s.survey_id ,
q.question_id,
q.question_text,
a.answer_id,
a.answer_text
FROM Survey s INNER JOIN
Question q ON s.survey_id = q.survey_id INNER JOIN
Answer a ON q.question_id = a.question_id
的INNER JOIN
旨意确保你只有在有可用的问题和答案的调查。
如果您想返回所有的调查,无论他们是否有问题或答案,或不管答案的问题,甚至所有的调查,你可以使用LEFT JOINS
SELECT s.survey_id ,
q.question_id,
q.question_text,
a.answer_id,
a.answer_text
FROM Survey s LEFT JOIN
Question q ON s.survey_id = q.survey_id LEFT JOIN
Answer a ON q.question_id = a.question_id
你必须尝试并且记住LEFT JOUN状态
返回左侧表格中的所有数据,仅返回右侧与左侧相匹配的数据。
看看这篇文章,它做了一个很好的图形解释。
如果我想,我可能用户where子句其中s.survey_id =用户在运行时在用户提供的 – user1553768 2012-07-30 04:33:41
在那里没有answer_text我也想answer_text – user1553768 2012-07-30 04:42:04
select
survey.survey_id ,
question.question_id,
question.question_text,
answer.answer_id
from survey
left join question on question.survey_id = survey.survey_id
left join answer on answer.question_id = question.question_id
我考虑到,所以我给的答案,所以你得到的答案表中的所有行
$select = "SELECT a.answer_id,a.answer_text,q.question_id, q.question_text,s.survey_id,s.survey_title FROM Answer a "
. "LEFT JOIN Question q ON (a.question_id = q.question_id) "
. "LEFT JOIN Survey s ON (q.survey_id = s.survey_id)";
我正在写这个querry这样,它是给sql语法错误从survey_answer_master选择a.answer_id,answer_text,q.question_id,q.question_text,s.survey_id,s.suvrey_title left join on survey_question_master q a.question_id = q.question_id left join on survey_master s q.survey_id = s.survey_id – user1553768 2012-07-30 04:49:14
我改变了代码。再次尝试 – 2012-07-30 04:51:08
errro显示您的SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便在第二行附近使用'a.question_id = q.question_id left join survey_master on s q.survey_'在第二行使用正确的语法 – user1553768 2012-07-30 04:57:25
尝试新鲜事物,喜欢阅读手册的一个问题可以有不止一个答案? – 2012-07-30 04:28:34
可能重复[如何从三个表中选择所有数据使用mysql中的连接](http://stackoverflow.com/questions/11715280/how-to-select-all-data-from-three-tables-using-joins -in-mysql) – 2012-07-30 04:31:30