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

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

但是执行JOINS时存在问题

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

table :

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

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

{
   "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]});
    }
});

10-06 12:56