【发布时间】:2019-10-23 23:42:37
【问题描述】:
我有两张表 NEW_TBL 和 CURRENT_TBL。
CURRENT_TBL 中的值需要更新,使其等于 NEW_TBL。两个表都有一个名为 tableId 的 PK,但 NEW_TBL 中的列并不总是匹配 CURRENT_TBL。我已经有了使架构相同所需的东西,但我需要一种基于动态列引用更新 CURRENT_TBL 值的方法。
这是我如何在 javascript 中完成此操作的人为示例。
起始表:
currentTable = [
['tableId','col2','col3','col4'],
['1','purple','blue','pink'],
['2','purple','red','orange'],
['3','green','yellow','purple']
];
newTable = [
['tableId','col2','col3','col4'],
['1','','blue','pink'],
['2','magenta','blue','pink'],
['4','grey','black','white']
];
功能:
function updateCurrentTable() {
var currentHeader = currentTable[0];
var newHeader = newTable[0];
var currentValues = currentTable.slice(1);
var newValues = newTable.slice(1);
var newIdList = newValues.map(function(val){ // Get list of newTable ids
return val[0];
})
var currentIdList = currentValues.map(function(val){ // Get list of newTable ids
return val[0];
})
for (var newColumn = 0; newColumn<newHeader.length; newColumn++) { // Loop through new table columns
var columnName = newHeader[newColumn];
var newIdColumn = newHeader.indexOf('tableId');
var currentColumnIndex = currentHeader.indexOf(columnName);
var currentIdIndex = currentHeader.indexOf('tableId');
if (columnName !== 'tableId') { // The tableId column is skipped because the id will never be altered
for (var newRow = 0; newRow<newValues.length; newRow++) { // Loop through new table rows
var newId = newValues[newRow][newIdColumn];
var newValue = newValues[newRow][newColumn];
if (currentIdList.indexOf(newId) < 0) { // If tableId exists in newTable but not in currentTable, add the row to currentTable
currentValues.push(newValues[newRow]);
currentIdList.push(newId); // Update the id list
}
for (var curRow =0; curRow < currentValues.length; curRow++) { // Loop through current table rows
var currentId = currentValues[curRow][currentIdIndex];
if (currentColumnIndex !== currentIdIndex) { // The tableId column is skipped because the id will never be altered
if (newIdList.indexOf(currentId) < 0) { // If tableId exists in currentTable but not newTable, remove the row from currentTable
currentValues.splice(curRow,1);
} else if (newId === currentId) { // If the tableIds match, update the value in the current column
currentValues[curRow][currentColumnIndex] = newValue;
}
}
}
}
}
}
Logger.log(currentValues)
}
结果:
currentTable = [
['tableId','col2','col3','col4'],
['1','','blue','pink'],
['2','magenta','blue','pink'],
['4','grey','black','white']
];
有没有办法在 SQL 中完成上述操作?
谢谢!
【问题讨论】:
标签: mysql database stored-procedures sql-update compare