0

我正在使用 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 并创建一个数组来推送子项?

4

1 回答 1

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);
于 2016-12-21T23:54:39.393 回答