将选择结果添加到另一个选择中并创建一个JSON密钥

时间:2019-07-17 14:49:00

标签: mysql sql mariadb

我创建了一个查询,该查询返回了survey表中所有不在survey_completion中并且属于user_Id = 1的调查:

我的功能查询是:

SELECT * 
FROM `survey` 
WHERE id NOT IN (
    SELECT `survey_id`
    FROM `survey_completion` 
    WHERE `user_id` = 1)

此查询的结果是,我想选择表question中的每一行,其中行question.survey_id = survey.id,然后将其作为JSON响应中的questionsList键返回< / p>

我将此添加到了查询中,但是它不起作用:

AND (SELECT *
     FROM question
     WHERE question.survey_id = survey.idas) AS questionsList

MariaDB在AS前缀上返回错误,我无法解决此问题

有人知道我该如何解决吗?

提供更多详细信息

我想要返回的查询是:

id: 1
name: 'test'
questionsList [
  {
    id: 1
    survey_id: 1
    question: 'How are you?'
  }
]

目前我的表survey具有行id, name,而我的表question具有行id, survey_id, question, user_id

因此,我想附加到每个与survey_id具有相同survey的ID的问题,将此列表作为JSON中的新嵌套列表获取并返回键名{{1} }

EDIT :听说过UNION可以做到这一点,对我来说这很有用,但是两个表的列不同吗?

1 个答案:

答案 0 :(得分:0)

在查询中构建JSON有点麻烦,但是我认为以下方法可以工作..并在每次调查中返回一行

   SELECT JSON_OBJECT(
            "id", s.id,
            "name", s.name,
            "questionList", JSON_ARRAYAGG(
              JSON_OBJECT(
                "id", q.id,
                "question", q.question 
              )  
            )
          ) survey_object
     FROM survey s /** surveys **/

     JOIN question q /** with their questions */
       ON q.survey_id = s.id 

LEFT JOIN survey_completion sc /** with their completions by user 1 */ 
       ON sc.survey_id = s.id
      AND sc.user_id = 1

    WHERE sc.survey_id IS NULL /** where there are no completions by user 1 */  

 GROUP BY s.id /** grouped by survey */