2

We have 2 tables. Question which has a question and Answers which has possible answer's for that question.

I want to collect all the questions such that all the answers for a given question appear in form of array.

select Answers.question_Id as questionId, 
       group_concat(json_array(Answers.answer)) as answers
      from Question 
      inner join Answers 
      on Question.id = Answers.question_Id 
      group by questionId

When I tried the above query I get the following output :

------------------------------------
questionId | answers
--------------------------
1          | ["1"],["2"],["3"],["4"]
------------------------------------

So I tried the following query :

select Answers.question_Id as questionId, 
          json_array(group_concat(Answers.answer)) as answers
          from Question 
          inner join Answers 
          on Question.id = Answers.question_Id 
          group by questionId

I get following output :


questionId | answers
--------------------------
1          | ["1,2,3,4"]
--------------------------

What I am looking for is ['1', '2', '3', '4']

Any suggestions what would be a good way. I also tried using only group_concat but it separates the output by comma and there are high chances that the answer will have comma in it. I was looking for a simple solution.

MySQL version : 5.7.19

2
  • Why do you need JSON output? Commented Mar 23, 2018 at 11:37
  • actually I need it in form of array Commented Mar 23, 2018 at 12:37

1 Answer 1

3

If you are using MySQL 5.7.22 or later, you may use the JSON_ARRAYAGG function:

SELECT
    a.question_Id AS questionId, 
    JSON_ARRAYAGG(a.answer) AS answers
FROM Question q
INNER JOIN Answers a
    ON q.id = q.question_Id 
GROUP BY
    a.question_Id
Sign up to request clarification or add additional context in comments.

2 Comments

We are using MYSQL 5.7.19
Then you may be somewhat out of luck. There might be a UDF which can do this. Are you using MySQL with an app language, such as Java or C#? They can easily handle your requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.