我们有2张桌子。问题包含question
和答案,该问题可能answer
。
我想收集所有问题,以便给定问题的所有答案都以数组的形式出现。
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
当我尝试上述查询时,我得到以下输出:
------------------------------------
questionId | answers
--------------------------
1 | ["1"],["2"],["3"],["4"]
------------------------------------
所以我尝试了以下查询:
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
我得到以下输出:
questionId | answers
--------------------------
1 | ["1,2,3,4"]
--------------------------
我要找的是['1', '2', '3', '4']
任何建议什么是好方法。 我也尝试过只使用group_concat,但它用逗号分隔输出 并且很有可能答案中会有逗号。 我一直在寻找一个简单的解决方案。
MySQL版本:5.7.19
答案 0 :(得分:2)
如果您使用的是MySQL 5.7.22
或更高版本,则可以使用JSON_ARRAYAGG
功能:
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