node.js oracledb - 使用数组为每个组获取一条记录

时间:2016-12-21 20:44:09

标签: javascript sql node.js oracle oracledb-npm

我使用node.js和OracleDB连接2个表,具有一对多的关系。

例如:

RECORDS Table:
RECORD_ID   COMMENTS
1000        Comment 1
1001        Comment 2

设备表:

DEVICE_ID   REF_RECORD_ID   DEVICE_NAME
2000        1000            iPhone 6
2001        1000            iPhone 7
2003        1001            Samsung Galaxy S6
2004        1001            Samsung Galaxy S7

我可以使用

检索联接
SELECT A.RECORD_ID, A.COMMENT, B.DEVICE_ID, B.DEVICE_NAME FROM RECORDS A, DEVICES B WHERE A.RECORD_ID = B.REF_RECORD_ID;

当前结果:

[{
    RECORD_ID: 1000, COMMENT: "Comment 1", DEVICE_ID: 2000, DEVICE_NAME: "iPhone 6"
},
{
    RECORD_ID: 1000, COMMENT: "Comment 1", DEVICE_ID: 2001, DEVICE_NAME: "iPhone 7"
},
{
    RECORD_ID: 1001, COMMENT: "Comment 2", DEVICE_ID: 2003, DEVICE_NAME: "Samsung Galaxy S6"
},
{
    RECORD_ID: 1001, COMMENT: "Comment 2", DEVICE_ID: 2004, DEVICE_NAME: "Samsung Galaxy S7"
}]

但我想得到如下结果:

[{
    RECORD_ID: 1000, COMMENT: "Comment 1",
    DEVICES: [{ DEVICE_ID: 2000, DEVICE_NAME: "iPhone 6" }, { DEVICE_ID: 2001, DEVICE_NAME: "iPhone 7" }]
},
{
    RECORD_ID: 1001, COMMENT: "Comment 2",
    DEVICES: [{ DEVICE_ID: 2003, DEVICE_NAME: "Samsung Galaxy S6" }, { DEVICE_ID: 2004, DEVICE_NAME: "Samsung Galaxy S7" }]
}]

有没有更好的方法来实现这一点,而不是循环遍历对象数组,然后找到重复的RECORD_ID并创建一个数组来推送子项?

1 个答案:

答案 0 :(得分:0)

您指定的输出可以在支持嵌套游标表达式时直接完成。你可以看到其他人在这里寻找同样的事情: https://github.com/oracle/node-oracledb/issues/565

同时,这里是一些代码的例子,一旦得到结果集,就可以在Node.js中执行此操作:

var resultRowsIdx;
var resultRows = [{
    RECORD_ID: 1000, COMMENT: "Comment 1", DEVICE_ID: 2000, DEVICE_NAME: "iPhone 6"
},
{
    RECORD_ID: 1000, COMMENT: "Comment 1", DEVICE_ID: 2001, DEVICE_NAME: "iPhone 7"
},
{
    RECORD_ID: 1001, COMMENT: "Comment 2", DEVICE_ID: 2003, DEVICE_NAME: "Samsung Galaxy S6"
},
{
    RECORD_ID: 1001, COMMENT: "Comment 2", DEVICE_ID: 2004, DEVICE_NAME: "Samsung Galaxy S7"
}];
var records = [];
var recordsMap = {};
var currentRecordId;

for (resultRowsIdx = 0; resultRowsIdx < resultRows.length; resultRowsIdx += 1) {
  currentRecordId = resultRows[resultRowsIdx].RECORD_ID;

  if (!recordsMap[currentRecordId]) {
    recordsMap[currentRecordId] = {};
    recordsMap[currentRecordId].RECORD_ID = currentRecordId;
    recordsMap[currentRecordId].COMMENT = resultRows[resultRowsIdx].COMMENT;
    recordsMap[currentRecordId].DEVICES = [];

    records.push(recordsMap[currentRecordId]);
  }

  recordsMap[currentRecordId].DEVICES.push({
    DEVICE_ID: resultRows[resultRowsIdx].DEVICE_ID,
    DEVICE_NAME: resultRows[resultRowsIdx].DEVICE_NAME
  });
}

console.log(records);