gpt4 book ai didi

mysql - 将 SQL 结果转换为 JSON 的正确方法

转载 作者:可可西里 更新时间:2023-11-01 07:38:29 25 4
gpt4 key购买 nike

我正在使用 nodejs 创建一个 API。 API 接受请求并以 JSON 格式响应

例如:我的数据库中有一个表 QUESTION,所以对端点 http://localhost/table/question 的 GET 请求将以 JSON 格式输出表格。

但是执行JOINS时出现问题

考虑表 QUESTION 和 CHOICE。一个问题有很多选择(答案)他们的加入将是

表格:

enter image description here

我正在尝试转换成这样的东西

{  
"0":{
"QUESTION":"If Size of integer pointer is 4 Bytes what is size of float pointer ?",
"OPTION":{
"A":"3 Bytes",
"B":"32 Bits",
"C":"64 Bits",
"D":"12 Bytes"
}
},
"1":{
"QUESTION":"Which one is not a SFR",
"OPTION":{
"A":"PC",
"B":"R1",
"C":"SBUF"
}
},
"2":{
"QUESTION":"What is Size of DPTR in 8051",
"OPTION":{
"A":"16 Bits",
"B":"8 Bytes",
"C":"8 Bits"
}
},
"3":{
"QUESTION":"Is to_string() is valid builtin function prior to c++11 ? ",
"OPTION":{
"A":"Yes",
"B":"No"
}
}
}

显而易见的解决方案是使用 JOIN 解析查询并将其转换为 JSON。有没有更有效的方法来做到这一点?

最佳答案

在 MySQL 中,您可以使用 group_concat 实现此目的

表名、字段名等纯粹是幻想:-)

select
q.text as question,
group_concat(answer.label, ';;;') as labels,
group_concat(answer.text, ';;;') as answers
from
question as q
join answer as a on a.quesion = q.id
group by
q.text

然后在你的应用程序(nodejs)中

let resultRows = callSomeFunctionsThatReturnesAllRowsAsArray();
let properStructure = resultRows.map(row => {
let texts = row.answers.split(';;;');
return {
question: row.question,
options: row.labels.split(';;;').map((label, index) => {label: label, answer: texts[index]});
}
});

关于mysql - 将 SQL 结果转换为 JSON 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47493874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com