如何使用连接从三个表中选择数据

时间:2012-07-30 04:25:50

标签: php mysql

我想从以下三个表格中选择survey_idquestion_idquestion_textanswer_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中的值时。

3 个答案:

答案 0 :(得分:3)

嗯,你可以从像

这样的东西开始
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状态

返回左侧表格中的所有数据,只返回右侧与左侧匹配的数据。

看看这篇文章,它做了一个很好的图解说明。

SQL SERVER – Introduction to JOINs – Basic of JOINs

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我正在考虑一个问题可以有多个答案,所以我给出了答案,以便获得答案表的所有行

 $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)";