0

我想从以下三个表中选择survey_idquestion_id和。question_textanswer_id

在 SurveyTable 我有:

Survey{survey_id,survey_title}

在 QuestionTable 我有:

Question{survey_id,question_id,question_text}

在答案表中:

Answer{question_id,answer_id,answer_text}

我想使用连接从这些表中进行选择。Whensurvey_id等于 QuestionTable 和 SurveyTable 中的值。

4

3 回答 3

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

s将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 – JOIN 简介 – JOIN 基础

于 2012-07-30T04:28:37.697 回答
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
于 2012-07-30T04:27:51.100 回答
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)";
于 2012-07-30T04:31:31.920 回答