将另一个表中的项数组连接到第一个表

时间:2016-12-02 07:44:14

标签: php mysql cakephp

我有一个表定义为。

survey_question_answers

    id  |  surveyId | questionId | title | description | creationDate

survey_questions
        id  |  surveyId | title | description | creationDate

我正在使用mysql查询

SELECT `SurveyQuestion`.*, `Answer`.* FROM `uaehub`.`survey_questions` AS `SurveyQuestion` LEFT JOIN `uaehub`.`survey_question_answers` AS `Answer` ON (`SurveyQuestion`.`id` = `Answer`.`questionId`)  WHERE `SurveyQuestion`.`id` = 1  GROUP BY SurveyQuestion.id

问题是,它只取一个答案而不是所有答案。如何修改查询以获取附加到surveyQuestion的所有答案

我想在cakephp

中这样做
$questions = $this->SurveyQuestion->find('all', array(   
                'conditions' => array('SurveyQuestion.id' => $survey['id']),
                'fields' => array(
                        'SurveyQuestion.*',
                        'Answer.*'
                ),
                'joins' => array(
                        array(
                                'type' => 'LEFT',
                                'table' => 'survey_question_answers',
                                'alias' => 'Answer',
                                'conditions' => array('SurveyQuestion.id = Answer.questionId')
                        ),                                                  
                ),
                'group' => array(
                        'SurveyQuestion'
                ),                
        ));

这就是我想要的

{
    "SurveyQuestion": {
      "id": "1",
      "surveyId": "1",
      "title": "Did you exercised early in the morning?",
      "description": "If Yes, please choose Yes. If no please choose NO",
      "creationDate": "2016-12-02 09:39:18"
    },
    "Answer": [{
      "id": "1",
      "surveyId": "1",
      "questionId": "1",
      "answer": "Yes",
      "creationDate": "2016-12-02 09:39:44"
    },
{
      "id": "2",
      "surveyId": "1",
      "questionId": "1",
      "answer": "NO",
      "creationDate": "2016-12-02 09:39:44"
    }]
  }
像这样的东西, 有一系列答案附在问题上

我得到的是

{
    "SurveyQuestion": {
      "id": "1",
      "surveyId": "1",
      "title": "Did you exercised early in the morning?",
      "description": "If Yes, please choose Yes. If no please choose NO",
      "creationDate": "2016-12-02 09:39:18"
    },
    "Answer": {
      "id": "1",
      "surveyId": "1",
      "questionId": "1",
      "answer": "Yes",
      "creationDate": "2016-12-02 09:39:44"
    }
  }

注意,这是cakephp的格式

1 个答案:

答案 0 :(得分:1)

为什么使用GROUP BY?这就是你只得到一行的原因。遗漏小组,它应该工作。

GROUP BY会将结果分组,以便(在您的情况下)对于任何surveyQuestion.id(=每个问题),只返回一行。